The template control allows you to separate the control data from its representation. The templated control does not provide a user interface.
Write it to implement a named container and classes that contain attributes and methods that can be accessed by the home page. MSDN explains this.
The following is a simple example:
1: create a custom template control MyTemplateControl. ascx
2: Define an ITemplate type attribute for the created template Control
3: Define a NamingContainer class for ITemplate
4: Apply TemplateContainer to attributes of the ITemplate type.
5. initialize the template data and add the template to the template container.
6: test the template control and bind data.
Sample Code:
MyTemplateControl. ascx
<% @ Control Language = "C #" AutoEventWireup = "true" CodeBehind = "MyTemplateControl. ascx. cs" Inherits = "FrameworkWebStudy. MyTemplateControl" %>
<Asp: PlaceHolder ID = "PlaceHolder1" runat = "server"> </asp: PlaceHolder>
Only one container is defined. Contains template control data.
Private ITemplate template = null;
[TemplateContainer (typeof (ContentContainer)]
[PersistenceMode (PersistenceMode. InnerProperty)]
Public ITemplate ContentTemplate
{
Get {return template ;}
Set {template = value ;}
}
The template container must implement the INamingContainer interface, which is only a tag interface,
Any control that implements this interface creates a new namespace. In this new namespace,
All child control IDs are unique within the application.
Public class ContentContainer: Control, INamingContainer
{
Private string m_content;
Public ContentContainer (string content)
{
M_content = content;
}
Public string Content
{
Get {return m_content ;}
}
}
Initialize some test data and add it to the Page_Init method of the control.
Void Page_Init ()
{
If (template! = Null)
{
String [] content = {"henry", "yunyun", "onlyone", "onely "};
For (int I = 0; I <content. GetUpperBound (0); I ++)
{
ContentContainer container = new ContentContainer (content [I]);
Template. InstantiateIn (container );
PlaceHolder1.Controls. Add (container );
}
}
}
Application Example:
<Form id = "form1" runat = "server">
<Div>
<Uc1: MyTemplateControl ID = "MyTemplateControl1" runat = "server">
<ContentTemplate>
Content: <asp: Label ID = "lblContent" runat = "server" Text = '<% # Container. Content %>'> </asp: Label>
</ContentTemplate>
</Uc1: MyTemplateControl>
</Div>
</Form>
Bind data:
Page. DataBind ();
Running result: