说明:web自定义控件与Winows自定义控件创建差不多,主要区别在于是否要显示出来,从而各自的基类不同
web自定义控件继承于System.Web.UI.Webcontrols.WebControl
下面是创建一般过程:
1:新建web控件库项目,实现INamingContainer接口。
2:为控件添加属性,如<input type="button"/>中的type。
3:重载CreateChildControls()方法,创建复合控件,并为子控件添加必须的方法。
简单的例子如下:
using System;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
using System.Drawing;
namespace MyLabel
{
public class MyLabel : WebControl, INamingContainer
{
public MyLabel()
{
}
private string message;
public string Message
{
get { return message; }
set { message = value; }
}
private Label tempLabel;
protected override void CreateChildControls()
{
this.Controls.Add(new LiteralControl("<h1>a simple test</h1><br/>"));
tempLabel = new Label();
tempLabel.Text = Message;
tempLabel.ForeColor = Color.Red;
this.Controls.Add(tempLabel);
this.Controls.Add(new LiteralControl("<br/>"));
Button tempButton = new Button();
tempButton.Text = "CHANGE COLOR";
tempButton.Click += new EventHandler(this.Button_Click);
this.Controls.Add(tempButton);
}
protected void Button_Click(object sender, EventArgs e)
{
tempLabel.ForeColor = Color.Blue;
}
}
}