白天有雨

此处应该有掌声

导航

自定义控件(支持模板)

基于模版的简单控件
<%@ 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"));
   }
   
  }
  }
}

posted on 2005-11-23 16:48  卓如  阅读(259)  评论(0编辑  收藏  举报