2012-09-20

Set SkinID for a Custom Controller

SkinID property should set in or before the Page_PreInit event for static controls. Since Custom Controller is written within a class, not a page, there are no page events available to set the SkinID. So, to set the SkinID property for a Custom Controller, you have to override it in the implementation of the custom controller class as below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using System.Web.UI.Adapters;

namespace WebApplication2
{
    [ToolboxData("<{0}:Class1 runat=\"server\"  SkinID=\"Skin1\"> </{0}:Class1>")]
    public class Class1 : Label
    {
       public override string SkinID
       {
           get
           {
               return "Skin2";
           }
           set
           {
               base.SkinID = value;
           }
       }

        protected override void Render(HtmlTextWriter writer)
        {
            Text = this.HeaderText;
            base.Render(writer);
        }

        [Bindable(true)]
        public String HeaderText
        {
            get
            {
                return (string)this.ViewState["HeaderText"] ?? String.Empty;
            }
            set
            {
                this.ViewState["HeaderText"] = value;
            }
        }
    }
}

I’m inheriting this custom controller from asp:Label class.

Skin file should be like below. Note that SkinID for the custom controller in this skin file is same as what I’ve returned in the class, when override the SkinID property. Since the skin file does not recognize the Custom Controller, we have to register it first using Register directive.

<%@ Register Assembly="WebApplication2" Namespace="WebApplication2" TagPrefix="cc2" %>
<cc2:Class1 runat="server" BackColor="Red"  ForeColor="White"  Font-Name="Arial"  Font-Size="9px" SkinID="Skin2" />

Now you can test it with the below ASPX code

<%@ Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="About.aspx.cs" Inherits="WebApplication1.About" %>

<%@ Register Assembly="WebApplication2" Namespace="WebApplication2" TagPrefix="cc2" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <cc2:Class1 ID="Class1" runat="server" HeaderText="Ruchira Gamage"> </cc2:Class1>
</asp:Content>

No comments: