OdeToCode IC Logo

Themes For ASP.NET User Controls

Tuesday, June 27, 2006

Q: I can't apply a Theme attribute to my user control. How am I supposed to theme and skin my user controls?

A: User Controls don't have a theme property, but when you assign a theme to a page, the theme does influence all of the controls in the page. A user control uses the theme of its page.

If the theme includes CSS files, then ASP.NET will link to the CSS files. Any styles inside the CSS that are applicable to classes, names, and markup in the user control will style the user control.

If the theme includes skins, then the skins will skin the appropriate controls inside of user controls. For instance, if you have defined a default skin for Calendar controls, then any Calendar controls inside your user control will have that skin applied.

It is also possible to apply a skin directly to the user control, we just need to know a couple tricks. First, let's define a simple user control: MyWidget. MyWidget just renders a Message property.

<%@ Control Language="C#" CodeFile="MyWidget.ascx.cs" Inherits="MyWidget" %>
<h1><%= Message %></h1>

The CodeFile for the control declares a Message property, but more importantly, adds a Themeable attribute to the control.

using System;
using System.Web.UI;

[
Themeable(true)]
public partial class MyWidget : System.Web.UI.UserControl
{
    
private string _message;
    
public string Message
    {
        
get { return _message; }
        
set { _message = value; }
    }
   
}

Finally, we just need a .skin file. We need to @ Register our control, and then write the skin just like we'd write any other skin.

<%@ Register Src="~/MyWidget.ascx" TagName="MyWidget" TagPrefix="otc" %>

<otc:MyWidget Message="Sahil Looks Funny" runat="server" />

Now, anytime we drop MyWidget on a page, the skin file will set a default message (assuming the control's page has a theme selected).