Welcome 微信登录

首页 / 网页编程 / ASP.NET / ASP.NET控件开发基础(4)

ASP.NET控件开发基础(4)2011-01-08Clingingboy一.从继承WebControl开始

在第二篇教程中,重点介绍了Render()方法的使用,用来呈现控件,但从Control类继承的控件尚未发挥asp.net控件的作用.大家知道web服务器控件分为HTML服务器控件(如<input id="Button2" runat="server" type="button" value="button" />这样的形式)和标准服务器控件(就是<asp:.. id="" runat="server"/>这样的形式的控件)

HTML服务器控件的控件从System.Web.UI.HtmlControls.HtmlControl 类派生

标准服务器控件的控件从System.Web.UI.WebControls.WebControl 类派生

HtmlControl 类和WebControl 类则从System.Web.UI.Control 类派生,并扩展.

所以我们说,所有的服务器控件都继承自System.Web.UI.Control 类,即所有的服务器控件都具有Control 类的共同属性,如Visible,EnableViewState属性,HtmlControl 类和WebControl 类则扩充了System.Web.UI.Control 类的功能,如

HtmlControl 类定义了所有 HTML 服务器控件所通用的方法、属性 (Property) 和事件(具体参数参照MSDN)

WebControl 类定义了所有标准服务器控件所通用的方法、属性 (Property) 和事件(具体参数参照MSDN)

如每个继承了WebControl 类的标准控件都有定义外观和行为的属性,然后不同控件再根据需要扩展功能.

图一

所以我们推荐的做法是直接从WebControl 类派生,而非Control类.我们所做的非并从头开始.从WebControl 类继承可以帮我们省很多工作.

二.重写WebControl类方法,不再是Render()

WebControl类继承了Control类,当然有Render方法,在WebControl类中重写了Render方法,如下代码

示例一

protected override void Render(HtmlTextWriter output)
{
RenderBeginTag(output);
RenderContents(output);
RenderEndTag(output);
}

注意 RebderBeginTag方法并非是HtmlTextWriter类中的方法,而是WebControl类中的方法,表示输出HTML标签头标记,如<table .....>,RenderEndTag方法则输出HTML标签尾标记,如</table>.中间的RenderContents方法则就是Control类的Render方法. 看下面RenderContents方法的定义.

示例二

protected override void RenderContents(HtmlTextWriter output){
//使用默认逻辑来呈现子控件,那么一定要调用基类中的方法。
base.Render(output);
}

接着再看RenderBeginTag方法的定义