different user control type: reuse layout vs reuse data

来源:互联网 发布:coc治疗药水数据 编辑:程序博客网 时间:2024/06/05 07:27

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 toprovide 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 placeholderPlaceHolderAddressTemplate.Controls.Clear();if (LayoutTemplate == null){PlaceHolderAddressTemplate.Controls.Add(new LiteralControl("No template defined."));}else{AddressUcContainer container = newAddressUcContainer(this.Address);this.LayoutTemplate.InstantiateIn(container);//add the controls to the placeholderPlaceHolderAddressTemplate.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 profileAddressUcTemplated1.Address.AddressLine1 = "1234 Some St.";AddressUcTemplated1.Address.City = "Ann Arbor";AddressUcTemplated1.Address.State = "MI";AddressUcTemplated1.Address.PostalCode = "48888";//bind data to controlsPage.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>



原创粉丝点击