Design a Brandable User Interface by Using Themes
Themes allow you to build sites with a consistent layout. You can set them up by adding an App_Themes directory for your application, and fill it up with folders. Each folder in the App_Themes directory represents a theme. You can assign them in a number of ways, in each case using the folder name to identify the theme.
There are five levels of applying themes:
- @Page Theme
- Web.config <pages Theme=””>
- Local control attributes
- @Page StyleSheetTheme
- Web.config <pages StyleSheetTheme=””>
A level at the beginning of the list overrides one at the end. So when you set a theme in the Page directive, it will override all the other style settings.
You can apply a theme programmatically, too. However, you must do this in a very early stage of the page lifecycle (namely, in Page_PreInit), and you can only set it in individual pages. The following code populates a DropDownList to let your users select a theme, stores the selected theme in a cookie, and retrieves it at Page_PreInit. The code itself:
protected void Page_Load (object sender, EventArgs e)
System.IO.DirectoryInfo di = new DirectoryInfo(Server.MapPath(@”~/App_Themes”));
DDList1.DataTextField = “Name”;
DDList1.DataSource = di.GetDirectories();
protected void DDLis1_SelectedIndexChanged(object sender, EventArgs e)
Response.Cookies.Add(new HttpCookie(“Theme”, DDList1.SelectedItem.Text));
protected void Page_PreInit (object sender, EventArgs e)
if(Request.Cookies[“Theme”] != null)
Page.Theme = Request.Cookies[“Theme”].Value;
This code is a little crappy, because you’ll only see the new theme applied after two postbacks (this is because of the order in which the events are fired and processed, and the page life cycle), so you should place it on a dedicated site (for example on a user profile site), and check for the Theme cookie in the Page_PreInit event of a master page.
You can even share themes within applications and sites. To do so, you must put your global themes in the IISDefaultRoot/Aspnet_Client/System_Web/version/Themes folder, on your server. Then the themes specified here will be available to your application just like if they were contained within it. There’s only one thing to remember: global themes never get overridden by a local theme defined with a same name.
Themes can contain for example CSS files, skin files, images, subfolders, etc. The most interesting ones are the skin files. In them, you can define general rules to controls, such as the background color of all your buttons. You can define specific rules, also, marked with a SkinID (which has its pair SkinID on the control you wish to apply the rules). For example, the Logout button should be shown in a different background color than the other ones on a page. Notes that there are limits of what properties can be controlled in a skin file. Generally, the ones that are related with the layout of a control can be set, while events, data sources, etc. cannot.