首页 > Web开发 > 详细

asp.net模板控件示例

时间:2014-03-12 19:59:20      阅读:443      评论:0      收藏:0      [点我收藏+]
原文: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>


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

 

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


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

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

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

 

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


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

bubuko.com,布布扣
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);
      }
    }
}
bubuko.com,布布扣


 

应用示例:

 

bubuko.com,布布扣
<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>
bubuko.com,布布扣

绑定数据:

Page.DataBind();


运行结果:

bubuko.com,布布扣 

asp.net模板控件示例,布布扣,bubuko.com

asp.net模板控件示例

原文:http://www.cnblogs.com/lonelyxmas/p/3597021.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!