基于模版的简单控件
1@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="WebApp3.WebForm1"
1@ Register TagPrefix="MY" NameSpace="WebApp3" Assembly="WebApp3"
1<html>
2<head>
3<title>WebForm1</title>
4<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"/>
5<meta content="C#" name="CODE_LANGUAGE"/>
6<meta content="JavaScript" name="vs_defaultClientScript"/>
7<meta content=" http://schemas.microsoft.com/intellisense/ie5 " name="vs_targetSchema"/>
8</head>
9<body ms_positioning="GridLayout">
10<form id="Form1" method="post" runat="Server">
11<my:mytemplatec runat="Server" text="button">
12<itemtemplate>
13<asp:button runat="server" text="```
14# Container.Text
15```"></asp:button>
16</itemtemplate>
17</my:mytemplatec>
18</form>
19</body>
20</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
{
///
1<summary>
2/// MyTemplateC 的摘要说明。
3/// </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"));
}
}
}
}