Code in Style with ASP.NET Themes

By Thiru Thangarathinam

Themes are rich skin templates available in ASP.NET 2.0 that allow you to define the look of pages and controls, which can then be applied to all the pages in your application to provide consistency for the entire application. A skin is a set of properties and templates that can be used to standardize the size, font, and other characteristics of controls on a page. A theme incorporates multiple skins and stylesheets to specify the overall look and feel of a Web site. Themes and skins will be simple to package, transfer, and apply to other Web sites. Themes are extremely flexible in that they can be applied to an entire Web application, page, or individual control. Theme files are stored with the extension .skin, and all the theme files for a Web application are stored in a special folder named Themes. ASP.NET 2.0 ships with several themes out of the box. It is also possible for you to create custom theme files. In the next section, we will see how to use pre-defined themes supplied with ASP.NET 2.0.

How Themes Work

A theme can consist of a combination of a css file and one or many skin files to control how ASP.NET server controls are rendered. These files are all contained within a folder, the name of which determines the theme. This folder, in turn, resides within a parent Themes folder. Any subfolders of the Themes folder act as themes for a site. For example, if you have a folder called ControlsTheme within the Themes folder, you can apply that theme to a page using the following declaration.

<%@ pagetheme="ControlsTheme"language="C#"%>

Once you place the theme attribute in the page directive, all the controls in that page automatically inherit the theme.

Using Pre-Defined Themes

ASP.NET ships with some standard themes that you can try out for yourselves, including ones such as BasicBlue and SmokeAndGlass. Let us take a look at an example to understand how to use one of the pre-defined themes in an ASP.NET page.

<%@ pagetheme="BasicBlue"language="C#"%>

<html>

<headrunat="server">

<title>Using Pre-defined Themes</title>

</head>

<body>

<formrunat="server">

<asp:labelid="Label1"runat="server"width="232px">This page uses

BasicBlue as its theme</asp:label>

<br/><br/>

<asp:textboxid="TextBox1"runat="server">

</asp:textbox>

<br/>

<br/>

<asp:buttonid="Button1"runat="server"text="Button"/>

<br/>

 

</form>

</body>

</html>

Navigating to the above page using the browser results in the following output.

Creating Custom Themes and Applying Them to the Pages

There are times when the built-in themes supplied with ASP.NET 2.0 may not meet your needs. In that case, you may want to create custom themes and apply them consistently to all the pages in your Web application. Creating custom themes in ASP.NET is a very simple process. All you need to do is create a special folder named Themes and place all your skins under that folder. Once you place the required .skin files under the Themes folder, they automatically become available to all the pages in the Web site.

Creating Custom Themes
This section explains how to create custom themes and use them in an ASP.NET pages. To create custom skins, you need to create .skin files and save them under the theme folder, which represents a specific theme. Skins look a bit like ASP.NET files in that they contain server control definitions and are used to alter the visual appearance of ASP.NET elements. Here are the steps for creating custom themes.

  • In Visual Studio.NET Whidbey, create a new folder named Themes by right clicking on the Web site name and selecting New Folder from the context menu. Note that the name "Themes" is pre-defined and must only be used to hold custom themes.
  • Once the Themes folder is created, right click on the Themes folder and select New Folder from the context menu to create a folder named ControlsTheme. The name of the folder is the name of the theme that will be used in different ASP.NET pages to refer to this theme.
  • Now, right click on the ControlsTheme folder and select Add New Item from the context menu. In the Add New Item dialog box, select Text File from the list and enter the name of the file as Label.skin. As you can see from the name of the file, this will be used to hold the style and formatting for a label control. Once the Label.skin is created, add the following code to the Label.skin file.

<asp:labelrunat="server"width="300px"height="24px"font-bold="True" font-overline="True"font-size="Medium"forecolor="Green"backcolor="Silver"/>

  • Note that the above code does not contain the id attribute for the label control since that needs to be specified in the pages that use the themes. The above line of code will automatically apply the specified formatting to any asp:label elements that are placed on a page to which the ControlsTheme is applied. The control definitions must include a runat="server" attribute, but they should never include an id attribute. Also, the style attributes for a control can be set to standard styles, or linked to the styles defined in a CSS sheet.
  • Now that we have created a skin for the label control, let us create a skin file for the button control as well. To do this, again right click on the ControlsTheme folder and select Add New Item from the context menu. In the Add New Item dialog box, specify the name of the .skin file as Button.skin. After the file is created, modify the file contents to look like the following.

<asp:buttonrunat="server"forecolor="RoyalBlue"backcolor="Silver"/>

  • So far, we have created the styles for a button control and a label control. Now that we have created these custom skins file, we can apply these consistently to all the pages in the Web site, providing a consistent look and feel for the entire Web application. Note that we have not specified the id attribute in the control declarations since the control that is actually inheriting this style will have its own id attribute.
As you have seen, a skin file can be used to apply styling and formatting to any ASP.NET element on a page, but they can't be used to specify attributes that are non-visual. For example, using the above .skin files, you can't specify a standard NavigateUrl attribute to be applied to all asp:hyperlink controls on a site. This is a design feature that will help to ensure that the skin files can only be used to apply formatting to a page.

Applying Custom Themes to an ASP.NET Page
Once you create the custom themes, applying them to individual ASP.NET pages is very simple. Basically you need to follow the same process that we used for applying built-in themes to an ASP.NET page. For the purposes of this example, let us create an ASP.NET Page named CustomThemes.aspx and modify the code in the page to look like the following.

<%@ page theme="ControlsTheme" language="C#" %>

<html>

<head runat="server">

<title>Applying Custom Themes to an ASP.NET Page</title>

</head>

<body>

<form runat="server">

<asp:button id="Button1" runat="server" text="This button inherits the style specified in the Button.skin file" />

<br/><br/>

<asp:label id="Label1" runat="server">This Label inherits the style specified in the Label.skin file</asp:label>

</form>

</body>

</html>

The above code is very simple and straightforward. We start by specifying the name of the theme as the value of the theme attribute. Then we have a label control and a button control in the page. As you can see, we haven't set any style attributes for these controls. But since we have already specified the skins for the button and the label control in the ControlsTheme folder, the controls in the page will automatically inherit the style settings specified in the skin files. If you navigate to the above page from the browser, you will see the following output.

The skins that we have created so far are called Control Skins, meaning that they automatically apply to all controls of the same type. For example, if you create a default control skin for a label control, the skin applies to all label controls on pages where you are using the theme. Control skins can be further classified into default skins and named skins. The skins we have created earlier are an example of default skins in which the skin is matched exactly by control type. For example, a button skin applies to all the button controls in the page. Named skins are skins for which you must assign a skinid identifier and then use that in different pages to reference it. This approach is very flexible in that you can add multiple entries for the same type of control to a skin file, uniquely identifying each one using a skinid attribute. This means you can have more than one style for a label control on a page. Let us demonstrate this by looking at an example. For this example, let us add one more skin named TextBox.skin to our ControlsTheme. After the file is created, we will add the following lines of code to it.

<asp:textbox skinid="lightGrayBackColor" runat="server" font-bold="True" font-size="Small" forecolor="RoyalBlue" backcolor="LightGray" font-italic="True"/>

<asp:textbox skinid="whiteBackColor" runat="server" font-bold="True" font-size="Small" forecolor="DarkGoldenrod" backcolor="GhostWhite"

font-italic="True"/>

The above code contains the style for the textboxes. However, this is different from the previous skins (label.skin or button.skin) in that this skin file contains multiple styles for a textbox control. Each style is uniquely identified by the skinid attribute. The page that uses the above skin can uniquely identify each of the textbox styles by specifying the skinid attribute. Let us look at an example that illustrates this.

<%@ pagelanguage="C#"theme="ControlsTheme"%>

<html>

<headrunat="server">

<title>Named Skins Example</title>

</head>

<body>

<formrunat="server">

<asp:textboxid="TextBox1"skinid="lightGrayBackColor"

runat="server"width="392px">

This control uses the lightGrayBackColor

Skinid

</asp:textbox>&nbsp;<br/><br/><br/>

<asp:textboxid="TextBox3"skinid="whiteBackColor"runat="server"

width="392px">

This control uses the whiteBackColor skinid

</asp:textbox>

 

</form>

</body>

</html>

The above code starts by specifying the Theme attribute in the Page directive. Then it declares two textboxes with each one containing different text. As you can see from each of the textbox declarations, they now contain a new attribute named skinid and the value of this attribute matches up with the value of the skinid attributes specified in the TextBox.skin file. Now if you navigate to the above page using a browser, you will see the following output.

As you can see from the above example, named skins offer us the flexibility to create multiple styles for the same control and then differentiate them by using the skinid attribute.

Accessing Themes Programmatically

There are times where you may want to programmatically set the theme for an ASP.NET page depending on certain parameters. For example, in a library management Web site, you might want to provide one theme for the visitors of the Web site and provide a completely different theme for the administrators of the Web site. You can easily accomplish this by setting the Theme property of the Page object to an appropriate value at runtime. The following code example shows how to set the Theme attribute of the page at runtime.

<%@ pagelanguage="C#"%>

<html>

<headrunat="server">

<scriptrunat="server">

void Page_PreInit(object sender, System.EventArgs e)

{

Page.Theme = "ControlsTheme";

}

</script>

<title>Dynamic Named Skins Example</title>

</head>

<body>

<formrunat="server">

<asp:textboxid="TextBox1"skinid="lightGrayBackColor"

runat="server"width="392px">

This control uses the lightGrayBackColor skinid

</asp:textbox>&nbsp;<br/><br/><br/>

<asp:textboxid="TextBox3"skinid="whiteBackColor"

runat="server"width="392px">

This control uses the whiteBackColor skinid

</asp:textbox>

</form>

</body>

</html>

The above code is very similar to our previous example except that in this case, we set the Theme attribute for the Page at runtime using the Page.Theme property. Note that you can set the Theme attribute only in the Page_PreInit event.

Configuring Themes Using the web.config File Settings

So far we have configured the Theme attribute using the Page directive. We have also seen an example where we set the theme of the page at runtime. Even though both of these approaches are very useful, you need to perform this in each and every page. This can be very tedious and can result in a lot of duplication of code, especially when all the pages in the Web site use the same theme. In that case, you can obviate the need to specifying the theme attribute in every page by setting the theme attribute in the pages element (that is present under system.web) in the web.config file. For example, the following line of code in the web.config file specifies that all the pages in the Web site will use the ControlsTheme as their theme.

<pages theme="ControlsTheme" />

All the pages in the application will use the above theme specified in the web.config file unless a Theme attribute appears in the Page declaration, in which case, the selected theme for that page will override the theme specified in the web.config file.

Themes and CSS

To apply a default stylesheet for a theme, all you need to do is create a .css file within the appropriate theme folder in the Themes directory. For example, you could place a css file called DefaultStyle.css within the Themes\DefaultStyle folder. When you specify the DefaultTheme in the theme attribute of the @page directive in a page, the DefaultStyle.css file is automatically applied. Note that you can still apply a stylesheet manually in the HTML by specifying the Link element in the head tag. You can actually place more than one stylesheet file within a theme folder - in which case ASP.NET will attempt to apply all stylesheets in that theme folder to the site, combining definitions contained in all the CSS files.

Themes versus CSS Style Sheets

Themes are similar to CSS style sheets in that both themes and style sheets define a set of common attributes that apply to any page where the theme or style sheet is applied. However, themes differ from style sheets in the following ways:

  • Themes can define many properties of a control or page, not just a specific set of style properties. For example, using themes, you can specify the graphics for a TreeView control, the template layout of a GridView control, and so on.
  • Themes can include auxiliary files, such as graphics, that can't be included in a CSS style sheet.
  • Themes do not cascade the way style sheets do; for example, theme property values always override local property values.
  • Themes can include style sheet references. In that case, the style sheet definitions are applied along with other property values defined in the theme.

Conclusion

This article has examined what themes are and how they can be used to provide a consistent look and feel for an entire Web application. We have also seen how to extend built-in themes by creating custom themes that can go a long way in customizing the look and feel of a Web site. Also covered was how to set the Theme property of the Page object at runtime using the Page.Theme property and how to set the theme for an entire Web site using the entries defined in the web.config file. Finally, the article looked at how to use existing CSS style sheets in conjunction with ASP.NET 2.0 themes, which makes it possible to leverage existing investments in CSS style sheets.

About the Author

Thiru has many years of experience in architecting, designing, developing and implementing applications using Object Oriented Application development methodologies. He also possesses a thorough understanding of software life cycle (design, development and testing).

He is an expert with ASP.NET, .NET Framework, Visual C#.NET, Visual Basic.NET, ADO.NET, XML Web Services and .NET Remoting and holds MCAD for .NET, MCSD and MCP certifications.

Thiru has authored numerous books and articles. He can be reached at thiruthangarathinam@yahoo.com.



Downloads

Comments

  • ghd rettetang Billig er ønsket velkommen av folk

    Posted by pletchersed on 06/14/2013 09:02am

    [url=http://ghdrettetangtilbud.qsite.dk/]ghd rettetang[/url] Rettetangen har roterende ledningfeste og tre ulike temperaturinnstillinger for ulike funksjoner og hårtyper, der makstemperaturen er 230 °C.Med den globale spenningsomformeren for 120-240V er rettetangen også perfekt å ha med på reisen, og du oppbevarer den sikkert i den medfølgende varmebestandige vesken i luksuriøs design.Elegant rettetang Paris som du både kan glatte og krølle håret med. [url=http://www.rettetangnorgenews.net/]ghd rettetang pris[/url] Katy Perry er nydelig uansett hva hun har på seg. Ikke mange kvinner ville matche håret til antrekket sitt, men Katy Perry er unntaket. Håret er en stadig skiftende regnbuen, og akkurat nå har hun valgt en mørk purple.I virkelig elsker Mermaid titt selv, det er noe så rent uskyldig om det, og jeg tror det er en fantastisk idé som GHD bruker dette bildet for deres annonse. Det gjør meg til å tenke, naturlig, breezy og lunefull. [url=http://www.rettetangnewsnorge.com/]ghd rettetang norge[/url] Når vi vet ghd rettetang norge kan opprette et utvalg av stilfull hår. Så vi ønsker alle å ha et slikt verktøy. For å lar oss easilycreate krøller og bølger, så vel som den perfekte rett hår. Men vet du hvilke ghd rettetang er det beste valget for deg. Vi bør velge ghd rettetang som passer for deg, heller enn å følge noen andres måte å kjøpe den.

    Reply
  • reviews after euphemistic pre-owned my clarisonic pro

    Posted by iouwanzi on 06/05/2013 10:50pm

    [url=http://www.miaclarisonicaustralia.org/]clarisonic mia 2[/url] Men hvis du ønsker at lytte til musik via en Bluetooth audio support uden at lukke dit problem stadig et kabel. Via USB giver dig de Beats by Dr. Dre Wireless på kort tid til 10 timers lytteglæde. Bare nyde i stil og trådløst fra din yndlingsmusik med Beats by Dr. Dre Wireless.The Beats Wireless leverer ligesom alle Beats By Dr. Dre produkter krystal klar diskant, naturlig mellemtone og en kraftfuld stram bas. Til også via bluetooth bedste præstation at levere den Beats Wireless med de nyeste Bluetooth-teknologi og er egnet til at modtage AAC og apt-X signaler. Selvfølgelig er dette Beats med ControlTalk. [url=http://www.australiaclarisonic.com/clarisonic-classic]clarisonic classic[/url] Som en atlet de ‘træning, som’, jeg gør, hvad jeg skal gøre for at blive klar “kan hovedtelefonen hjælper mig til at føle jeg er så meget tættere på min musik, der hjælper mig udføre, hjælper mig med at finde ud af, om jeg vil at være intens? Uanset hvad jeg ønsker at være på banen den dag, musik hjælper mig derhen. Da de sagde ja, vil produktet blive valgt og hjælpe dem med at opretholde den bedste tilstand I spillet.Ifølge en talsmand for selskabet, ved Dre endnu ikke har haft en dialog med IOC om “ambush marketing” praksis af atleter iført og twitte om de sanktioneret hovedtelefoner Beats. Men Omar Johnson, Beats senior VP for markedsføring, fortæller Billboard.biz at virksomheden arbejder med atleter året rundt. [url=http://www.australiaclarisonic.com/clarisonic-classic]clarisonic classic[/url] Dr. Dre Beats by Dre hovedtelefoner tendens til at være så dygtige i mange hovedtelefoner producerer. Blandt det store udvalg af Monster Beatshovedtelefoner med næsten alle håndsæt kan individuelt kunne være Fahion trend med blanding, med fremragende fordele. De behøver ikke nødvendigvis giver et individ af Dr. Dre hovedtelefoner som de to sider.

    Reply
  • Hvis du er ute etter billige hodetelefoner, Dr Dre inn

    Posted by mantouhmmm on 06/03/2013 11:56pm

    [url=http://www.beatsbynopro.manifo.com/]Beats By Dre[/url] Beats By Dre Expedition hodetelefoner forbli sterkt i tillegg til å holde på å være rolig muligens mens i lengre sykluser praktiske. Dette svingbare hodet k-kopper også gjøre det mulig for "one-ear" tilsyn. Innredet med en slags tre. 5-mm musikken stopper, er dette Bests Doctor Dre kompatibel ha praktisk talt bestemt jamming produkt. "Tatt i betraktning at Colossal rekorder elektrisk drevet design produksjon området syntes å være satt opp med 1924 har Bests dre bli identifiserbar ha tysk-laget satt på overdreven teknologisk kunnskap i den dyktige lydopptak teknologi segment. Små fordeler i forhold til Bests ved hjelp av Dre Dette Bests ved hjelp av dre Expedition valg av varer inneholder, sammen med mikrofoner i tillegg til lydopptak headset, hodetelefoner beregnet på Telly kommentatorer i tillegg til pilotene sammen med diskusjonen programmer i tillegg til å tolke etablissementer. [url=http://www.beatsbynopro.manifo.com/]Beats By Dre[/url] Designet for imponerende lyd, K551 50 mm drivere (nesten 2 inches, for de som er på keiserlige målinger) som støttes av Engineering ekte AKG bilde. Disse referansen førsteklasses hodetelefonene er utformet for å gi et fullt realistisk og naturtro gjengivelse av livet, og de gode sjåfører er grunnlaget for gjennomføring av lyden. Fast Image Engineering er utformet for å gi klarhet, dybde og avstand i musikk lytting. Lukkede tilbake beatsbre1 SJD gir støyisolering å holde uønsket støy fra mens lær innpakket, polstrede øreklokker hindre lyd lekker ut. AKG design er ikke bare verdifullt for ørene, men øynene samt lette og portable hodetelefoner er laget i klassisk stil med tidløs vinkler Andre funksjoner inkluderer. [url=http://www.drebeatsbysnorge.blinkweb.com/]beats by dre norge[/url] Bestem deg for hva din mor ville elske den største og å pynte gaven kurv pakk den opp pent med noen gave papirer og sette på noen blomster og bånd på den. Sett også et bilde av deg og din mor innrammet i den. Hun er bare overskriften å virkelig liker det. For å toppe det hele, også inneholde beats by Dr Dre solo hd personlig kort, og det er på vei til å være utmerket gave til en ideell billige beats av Dre på Mors day.AKG-produsent av high-end hodetelefoner, mikrofoner og høyttalere i over 60 år, kunngjorde i dag tilgjengeligheten av sin K551 håndsett. De lukkede tilbake bokser har en massiv drivere og realistisk lyd Passiv støyisolering for pue nedsenking.

    Reply
  • Deciding on a gucci? Check out this

    Posted by BobHotgloff on 05/01/2013 07:48am

    Extra short article content shows you the most important ins and outs of nike and the thing that you must do this afternoon. [url=http://www.mizunogoruhujp.com/]ミズノゴルフ[/url] The Root Key For mizuno [url=http://www.mizunogoruhujp.com/ミズノ-ゴルフクラブ-c-1.html]ミズノ mp[/url] Quick post helps you with the most important details for mizuno and consequently the things that you want to accomplish right now. [url=http://www.mizunogoruhujp.com/ゴルフグローブ-c-33.html]ミズノ グローブ[/url] Those things other people has been doing in regard to nike and furthermore the thing that you need to try and do completely different. [url=http://www.mizunogoruhujp.com/ゴルフバッグ-c-7.html]ミズノ[/url] Third party review shows 4 brand new stuff about nike that no-one is talking about. [url=http://www.mizunogoruhu.com/]ミズノ アイアン[/url] An essential double sprain on nike [url=http://www.mizunogoruhu.com/ミズノmizuno-クラブ-c-4.html]ミズノ グラブ[/url] Outfits and formation in Nevada : mizuno basically leaves without any see you later [url=http://www.mizunogoruhu.com/ミズノmizuno-アイアン-c-3.html]ミズノ[/url] Flourishing approaches for nike that you can use starting off right now. [url=http://www.mizunogoruhu.com/ミズノmizuno-バッグ-c-5.html]ミズノ[/url] Short posting illustrates the incontestable information about mizuno and in what way it might have an effect on your business.

    Reply
  • Creative nike Publication Disclose The Simplest Way To Rule The nike Marketplace

    Posted by icoppyapedcap on 04/24/2013 02:13am

    NpjDchBdpWvp [url=http://www.nikeyasuijp.com/]ナイキ[/url]VdfZshEdfIsg [url=http://www.nikeyasuijp.com/nike-air-force1エアフォース1-c-14.html]ナイキ フリ[/url]WavZbrLmxKfc [url=http://www.nikeyasuijp.com/nike-air-maxエアマックス-c-12.html]ナイキ エアマックス[/url]LjeKtzEciSwj [url=http://www.nikeyasuijp.com/nike-air-jordanエア-ジョーダン-c-13.html]nike free[/url]GwaLzhRpfCwh

    Reply
  • How to apply theme permanently.

    Posted by Siddharth Kajla on 10/28/2012 10:58pm

    As soon as we refresh the page theme effect will expires so how can we save them permanently so that after selecting theme the use will always see its selected theme ...so plz guide me for that.. Thank You

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • The explosion in mobile devices and applications has generated a great deal of interest in APIs. Today's businesses are under increased pressure to make it easy to build apps, supply tools to help developers work more quickly, and deploy operational analytics so they can track users, developers, application performance, and more. Apigee Edge provides comprehensive API delivery tools and both operational and business-level analytics in an integrated platform. It is available as on-premise software or through …

  • As mobile devices have pushed their way into the enterprise, they have brought cloud apps along with them. This app explosion means account passwords are multiplying, which exposes corporate data and leads to help desk calls from frustrated users. This paper will discover how IT can improve user productivity, gain visibility and control over SaaS and mobile apps, and stop password sprawl. Download this white paper to learn: How you can leverage your existing AD to manage app access. Key capabilities to …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds