Reuse layout: normal User Control
Reuse data: Templated User Control
http://www.codeproject.com/Articles/397646/A-Beginners-Tutorial-for-Understanding-Templated-U
- container :The main purpose of having this container class is to provide the
FindControl
functionality with the custom layout in place. The naming container-based class you’ll create inherits from Control and implements the INamingContainer interface
public class AddressUcContainer : Control, INamingContainer
{
public AddressUcContainer(Address address)
{
this.Address = address;
}
public Address Address { get; set; }
}
- implement a property of type ITemplate,Apply the TemplateContainerAttribute attribute to the ITemplate property; this marks the property as a template.
public partial class AddressUcTemplated :
System.Web.UI.UserControl
{
protected void Page_Init(object sender, EventArgs e)
{
//clear the controls from the placeholder
PlaceHolderAddressTemplate.Controls.Clear();
if (LayoutTemplate == null)
{
PlaceHolderAddressTemplate.Controls.Add(
new LiteralControl("No template defined."));
}
else
{
AddressUcContainer container = new
AddressUcContainer(this.Address);
this.LayoutTemplate.InstantiateIn(container);
//add the controls to the placeholder
PlaceHolderAddressTemplate.Controls.Add(container);
}
}
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateContainer(typeof(AddressUcContainer))]
public ITemplate LayoutTemplate { get; set; }
public Address Address { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
//simulate getting a user and loading his or her profile
AddressUcTemplated1.Address.AddressLine1 = "1234 Some St.";
AddressUcTemplated1.Address.City = "Ann Arbor";
AddressUcTemplated1.Address.State = "MI";
AddressUcTemplated1.Address.PostalCode = "48888";
//bind data to controls
Page.DataBind();
}
- How to use this template control
<uc1:AddressUcTemplated ID="AddressUcTemplated1"
runat="server" AddressType="Home">
<LayoutTemplate>
<h1>Edit Home Address</h1>
<table>
<tr>
<td>Address Line 1:</td>
<td>
<asp:TextBox ID="TextBoxAddress" runat="server"
Text="<%#Container.Address.AddressLine1%>"></asp:TextBox>
</td>
</tr>
<tr>
<td>Address Line 2:</td>
<td>
<asp:TextBox ID="TextBoxAddressLine2" runat="server"
Text="<%#Container.Address.AddressLine2%>"></asp:TextBox>
</td>
</tr>
<tr>
<td>City:</td>
<td>
<asp:TextBox ID="TextBoxCity" runat="server"
Text="<%#Container.Address.City%>"></asp:TextBox>
</td>
</tr>
<tr>
<td>State:</td>
<td>
<asp:TextBox ID="TextBoxState" runat="server"
Text="<%#Container.Address.State%>"></asp:TextBox>
</td>
</tr>
<tr>
<td>Postal Code:</td>
<td>
<asp:TextBox ID="TextBoxPostalCode" runat="server"
Text="<%#Container.Address.PostalCode%>"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="ButtonSave" runat="server" Text="Save"
OnClick="ButtonSave_Click"/>
</td>
</tr>
</table>
</LayoutTemplate>
</uc1:AddressUcTemplated>