Recipe 10.6. Using Themes


Problem

You want to be able to change the look of your application without having to change all the pages in your application.

Solution

Use the Theme features in ASP.NET 2.0 to define the look of your application. That is, create a theme to define the look of each control and set the Theme attribute of the @ Page directive to tell ASP.NET to use the theme for controls on the page.

Create a theme as follows:

  1. Create an App_Themes folder in the root of your application.

  2. Create a folder with the name you want to use for the theme in the App_Themes folder.

  3. Create a .skin file in the folder created above containing a definition for each server control you use in your application with the attributes that define its appearance set the way you want the control to look.

  4. (Optionally) Create a .css file in the folder created above to use with your .skin file.

  5. (Optionally) Add any images to the folder created above or to a subfolder as desired.

In the .aspx file for pages in your application set the Theme attribute of the @ Page directive to the name of the theme you want to use for the page.

The .skin files we created to demonstrate this solution are shown in Example 10-14 (blue theme) and Example 10-15 (grey theme). The .aspx file for the page that demonstrates how to use the theme is shown in Example 10-16. The code-behind file for the page is shown in Examples 10-17 (VB) and 10-18 (C#). The output for the page is shown in Figure 10-3.

Figure 10-3. Output of demonstration page using blue theme


Discussion

Providing a consistent look and feel for web applications has always been a challenge. In the early days of the web, all look and feel was hardcoded into the HTML in the pages. This was convenient but had two major drawbacks. First, ensuring that all pages had a consistent look and feel required a lot of work and QA testing. Second, changing the look and feel of the application required changing every page in the application. For a large site, this was generally an expensive project.

CSS greatly diminished the problem by providing the ability to define in one place the look and feel for all aspects of the HTML page and controls. This reduced the effort of ensuring a consistent look and feel as well as the magnitude of the effort to change it. Unfortunately, style sheets can get complicated. The complexity arises from some styles inheriting from "parent" styles resulting in a confusing hierarchy of style definitions.

ASP.NET 2.0 has introduced themes to help with the problem. Themes are a collection of CSS files, .skin files, and images. Themes do not replace style sheets. Themes are intended to complement style sheets and to place all of the files associated with a given look and feel in a single location.

In ASP.NET 2.0, a special folder named App_Themes in the root of your application is used to store themes. Each theme needed for your application is placed in a separate folder within the App_Themes folder, as shown in Figure 10-4.

Figure 10-4. Theme folder structure


The .skin files that are part of themes contain definitions of each of the server controls used in your application along with the look and feel that is desired for the controls. The server control definitions in .skin files look identical to the server controls placed in the .aspx files, except that the only defined aspects are the visual aspectsthat is, the look and feel. An example of the GridView control in the .skin file is shown below:

 <asp:GridView runat="server" BorderColor="#000080" BorderStyle="Solid" BorderWidth="2px" HorizontalAlign="Center" Width="90%"> <HeaderStyle HorizontalAlign="Center" Css /> <RowStyle css /> <AlternatingRowStyle css /> <SelectedRowStyle Css /> </asp:GridView> 

The control definitions in .skin files can contain an optional SkinID attribute to allow defining the same server control multiple times in a .skin file but with a different look and feel. This is useful when your application needs to use the same control in a page multiple times with different looks. When the SkinID attribute is not included in the control definition, the definition is used as the default definition.

 <asp:Button runat="server"    Css />     <asp:Button runat="server" Skin Css /> 

A combination of server control definitions in .skin files and .css files provides the best flexibility in defining the look and feel for an application.

The simplest way to use a theme is to set the Theme attribute in the @ Page directive to the name of the theme you want applied to the page. This results in the look and feel for the default server controls defined in the .skin file (the ones without a SkinID) for the theme being applied to the controls on the page.

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master"  AutoEventWireup="false"  CodeFile="CH10UsingThemesVB1.aspx.vb"  Inherits="ASPNetCookbook.VBExamples.CH10UsingThemesVB1"  Theme="Blue"  Title="Using Themes" %> 

To provide finer control over the application of the theme to a page, you can set the SkinID of individual controls to the SkinID of the control definition in the .skin file that you want applied to the control.

 <asp:Button  runat="server" Skin Text="Edit" /> 

In the web.config file, you can define the theme to be used by all pages in your application. By setting the theme in web.config, you will not need to set the Theme attribute in the @ Page directive of each page. This approach makes globally changing to another defined theme simple.

 <?xml version="1.0"?> <configuration>   <system.web> … <!- set the theme fo all pages to to eliminate the need to add a Themes attribute to the @ Page directive to each page. --> <pages theme="Grey" />   </system.web> </configuration> 

The Theme attribute of the @ Page directive can be set in individual pages to override the setting in web.config for individual pages.


Themes are an excellent addition to ASP.NET 2.0, providing the ability to define and maintain a consistent look and feel. Themes can even be personalized, as described in Recipe 10.6.

See Also

Recipe 10.6

Control Definitions in .skin Files Override Definitions in .aspx Files

The attributes defined for server controls in .skin files override the same definitions placed in .aspx files. Normally, this is the behavior you want, but be careful when defining some elements of complexserver controls, such as the GridView. For example, it might be tempting to place the following control definition in a .skin file:

 <asp:GridView runat="server" BorderColor="#000080" BorderStyle="Solid" BorderWidth="2px" HorizontalAlign="Center" Width="90%">   <HeaderStyle HorizontalAlign="Center" Css />   <RowStyle css />   <AlternatingRowStyle css />   <SelectedRowStyle Css />   <Columns> <asp:BoundField ItemStyle-HorizontalAlign="Left" /> <asp:BoundField ItemStyle-HorizontalAlign="Center"    DataFormatString="{0:MMM dd, yyyy}"/> <asp:BoundField ItemStyle-HorizontalAlign="Center"    DataFormatString="{0:C2}"/>   </Columns> </asp:GridView> 

This would seem to be all right since only look-and-feel attributes are defined. The problem arises, however, with the definition of the <Columns> element. The <asp:BoundField> elements will override the same elements in the control definition in the .aspx file. This problem results in a GridView containing no data because the <asp:BoundField> elements do not contain DataField attributes that define what data from a dataset gets bound to the column.


Example 10-14. Blue .skin file

 <asp:GridView runat="server" BorderColor="#000080" BorderStyle="Solid" BorderWidth="2px" HorizontalAlign="Center" Width="90%"> <HeaderStyle HorizontalAlign="Center" Css /> <RowStyle css /> <AlternatingRowStyle css /> <SelectedRowStyle Css /> </asp:GridView> <asp:Button runat="server" Css /> <asp:Button runat="server" Skin Css /> 

Example 10-15. Gray .skin file

 <asp:GridView runat="server"  BorderColor="#C0C0C0"  BorderStyle="Solid"  BorderWidth="2px"  HorizontalAlign="Center"  Width="90%"> <HeaderStyle HorizontalAlign="Center" Css /> <RowStyle css /> <AlternatingRowStyle css /> <SelectedRowStyle Css /> </asp:GridView> <asp:Button runat="server"    Css /> 

Example 10-16. Page using the blue theme (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH10UsingThemesVB1.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH10UsingThemesVB1" Theme="Blue" Title="Using Themes" %> <asp:Content  runat="server" ContentPlaceHolder> <div align="center" >   Using Themes - Blue (VB) </div> <asp:GridView  Runat="Server" AllowPaging="false" AllowSorting="false" AutoGenerateColumns="false" Caption="" EnableTheming="true" > <Columns>   <asp:ButtonField ButtonType="Link" CommandName="Select" Text="Select" />   <asp:BoundField HeaderText="Title" DataField="Title" ItemStyle-HorizontalAlign="Left" />   <asp:BoundField HeaderText="Publish Date" DataField="PublishDate" ItemStyle-HorizontalAlign="Center" DataFormatString="{0:MMM dd, yyyy}"/>   <asp:BoundField HeaderText="List Price" DataField="ListPrice" ItemStyle-HorizontalAlign="Center" DataFormatString="{0:C2}"/> </Columns> </asp:GridView> <br /> <table width="40%" border="0" align="center">   <tr>     <td align="center">   <asp:Button  runat="server"  Text="Add" /> </td>     <td align="center">       <asp:Button  runat="server"    Text="Edit" />     </td>     <td align="center">       <asp:Button  runat="server"    Text="Delete" />     </td>  </tr>    </table> </asp:Content> 

Example 10-17. Page using the blue theme code-behind (.vb)

 Option Explicit On Option Strict On Imports Microsoft.VisualBasic Imports System.Configuration.ConfigurationManager Imports System.Data Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code behind for ''' CH10UsingThemesVB1.aspx ''' </summary> Partial Class CH10UsingThemesVB1   Inherits System.Web.UI.Page   '''***********************************************************************   ''' <summary>   ''' This routine provides the event handler for the page load event. It   ''' is responsible for initializing the controls on the page.   ''' </summary>   '''   ''' <param name="sender">Set to the sender of the event</param>   ''' <param name="e">Set to the event arguments</param>   Private Sub Page_Load(ByVal sender As Object, _     ByVal e As System.EventArgs) Handles Me.Load     Dim dSource As SqlDataSource = Nothing Dim dataKeys(0) As String If (Not Page.IsPostBack) Then   'configure the data source to get the data from the database   dSource = New SqlDataSource()   dSource.ConnectionString = _   ConnectionStrings("dbConnectionString").ConnectionString   dSource.DataSourceMode = SqlDataSourceMode.DataReader   dSource.ProviderName = "System.Data.OleDb"   dSource.SelectCommand = "SELECT TOP 10 " & _   "BookID,Title,PublishDate,ListPrice " & _   "FROM Book " & _   "ORDER BY Title"   'set the source of the data for the gridview control and bind it   dataKeys(0) = "BookID"   gvBooks.DataKeyNames = dataKeys   gvBooks.DataSource = dSource   gvBooks.DataBind() End If End Sub 'Page_Load End Class 'CH10UsingThemesVB1 End Namespace 

Example 10-18. Page using the blue theme code-behind (.cs)

 using System; using System.Configuration; using System.Web.UI.WebControls; using System.Web.Profile; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code behind for /// CH10UsingThemesCS1.aspx /// </summary> public partial class CH10UsingThemesCS1 : System.Web.UI.Page {   ///***********************************************************************   /// <summary>   /// This routine provides the event handler for the page load event.   /// It is responsible for initializing the controls on the page.   /// </summary>   ///   /// <param name="sender">Set to the sender of the event</param>   /// <param name="e">Set to the event arguments</param>   protected void Page_Load(object sender, EventArgs e)   { SqlDataSource dSource = null; String[] dataKeys; if (!Page.IsPostBack) {   // configure the data source to get the data from the database   dSource = new SqlDataSource();   dSource.ConnectionString = ConfigurationManager.   ConnectionStrings["dbConnectionString"].ConnectionString;   dSource.DataSourceMode = SqlDataSourceMode.DataReader;   dSource.ProviderName = "System.Data.OleDb";   dSource.SelectCommand = "SELECT TOP 10 " +   "BookID,Title,PublishDate,ListPrice " +   "FROM Book " +   "ORDER BY Title";   // set the source of the data for the gridview control and bind it   dataKeys = new string[1] { "BookID" };   gvBooks.DataKeyNames = dataKeys;   gvBooks.DataSource = dSource;   gvBooks.DataBind();    }  } // Page_Load   } // CH10UsingThemesCS1 } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net