The Web Forms Template Customization Architecture provides a customization infrastructure that enables you, as a control developer, to build controls that are as lookless as possible, allowing you to separate control behavior from actual control appearance. Web page developers can take advantage of this functionality by designing custom templates that enable rich customization of controls, allowing precise control over the look and feel of controls and the pages that use them. Using custom templates, page developers might even create scenarios not envisioned by the original control developers.
ITemplate Instances
You can expose template customization support within your controls using get and set properties of type ITemplate. ITemplate objects provide a factory definition for dynamically customizingand creating a control instance by invoking the ITemplate.Initialize method.
For example, the following sample shows how a repeater control could have a custom ItemTemplate declaratively specified within a page:
<html> <script language="C#" runat=server> public void Page_Load(Object sender, EventArgs e) { ArrayList myList = new ArrayList(); myList.Add("DataItem One"); myList.Add("DataItem Two"); myList.Add("DataItem Three"); MyRepeater.DataSource = myList; MyRepeater.DataBind(); } </script> <body> <asp:repeater id="MyRepeater" runat=server> <template name="itemtemplate"> Here is the value in a text box: <input type=text value="<%#Container.DataItem%>" runat=server> </template> </asp:repeater> </body> </html>
The repeater control could then be implemented as follows:
public class RepeaterItem : Control, INamingContainer { public Object DataItem; public int Index; public RepeaterItem(Object dataItem, int index) { this.DataItem = dataItem; this.Index = index; } } public class Repeater : Control, INamingContainer { private ITemplate itemTemplate; private ICollection datasource; // Customizable template for each Item within the repeater public ITemplate ItemTemplate { get { return itemTemplate; } set { itemTemplate = value; } } // Datasource property to use to dynamically create rows within list public ICollection DataSource { get { return datasource; } set { datasource = value; } } // Framework method to dynamically create and initialize item rows in response // to a DataBind() call. protected override void OnDataBind(EventArgs e) { IEnumerator iterator = DataSource.GetEnumerator(); int index = 0; while (iterator.GetNext()) { // Construct a new RepeaterItem control instance – settings its dataitem // and index properties dynamically using appropriate values RepeaterItem item=new RepeaterItem(iterator.GetObject(), index); // Customize the item instance using the declarative template ItemTemplate.Initialize(item); // Add the control instance into the hierarchy tree this.Controls.Add(item); } } }