asp.net模板控件示例

模板控件允许将控件数据与其表示形式相分离,模板化控件不提供用户界面。

编写它则是为了实现一个命名容器以及包含属性和方法可由宿主页访问的类,MSDN是这样解释的。

 

下面是一个简单的示例:

 1:建立一个自定义模板控件  MyTemplateControl.ascx

 2:为建立的模板控件定义一个ITemplate类型的属性

 3:为 ITemplate 定义一个NamingContainer类

 4:应用TemplateContainer至ITemplate类型的属性上 。

 5:初始化模板数据,把 模板加至模板容器中。

 6:测试模板控件,绑定数据。

 

示例代码:

 MyTemplateControl.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyTemplateControl.ascx.cs" Inherits="FrameworkWebStudy.MyTemplateControl" %>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>


 只定义了一个容器。用于包含模板控件数据。

 

private ITemplate template = null;
        [TemplateContainer(typeof(ContentContainer))]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        
public ITemplate ContentTemplate
        {
            
get { return template; }
            
set { template = value; }
        }


模板容器,必须实现INamingContainer接口,这仅只是一个标记接口,

任何实现该接口的控件都创建一个新的命名空间,在这个新的命名空间中,

所有子控件 ID 在应用程序内是唯一的。

 

public class ContentContainer : Control, INamingContainer
    {
        
private string m_content;
        
public ContentContainer(string content)
        {
            m_content = content;
        }
        
public string Content
        {
            
get { return m_content; }
        }
    }


初始化一些测试数据,添加至控件的Page_Init方法中

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);
      }
    }
}


 

应用示例:

 

<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>

绑定数据:

Page.DataBind();


运行结果:

 

posted @ 2010-08-04 22:29  Repository  阅读(2206)  评论(0编辑  收藏  举报