基于模版的简单控件
<%@ Page language="c#" Codebehind="WebForm1.ASPx.cs" AutoEventWireup="false" Inherits="WebApp3.WebForm1" %>
<%@ Register TagPrefix="MY" NameSpace="WebApp3" Assembly="WebApp3" %>
<!DOCTYPE Html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="javascript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" Runat="Server">
<MY:MyTemplateC Text="button" runat="Server">
<ItemTemplate>
<asp:Button Text="<%# Container.Text %>" Runat=server></asp:Button>
</ItemTemplate>
</MY:MyTemplateC>
</form>
</body>
</HTML>.cs
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!this.Page.IsPostBack)
DataBind();
}
控件代码:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace WebApp3
{
/// <summary>
/// MyTemplateC 的摘要说明。
/// </summary>
[ParseChildren(true)]
public class MyTemplateC: Control,INamingContainer
{
private ITemplate itemPlate;
[TemplateContainer(typeof(MyTemplateC))]//指定当前控件类型
public ITemplate ItemTemplate
{
get{return itemPlate;}
set{itemPlate=value;}
} private string text;
public string Text
{
get{return text;}
set{text=value;}
}
protected override void OnDataBinding(EventArgs e)
{
this.EnsureChildControls();//确定是否包含子控件,否则创建
base.OnDataBinding (e);
} protected override void CreateChildControls()
{
if(itemPlate!=null)
{
itemPlate.InstantiateIn(this);//当由类实现时,创建子控件对象
}
else
{
this.Controls.Add(new LiteralControl(" NO TEMPLATE"));
}
}
}
}