创建类库项目buttonControl

buttonControl类库项目的myButton类
1
using System;
2
using System.Web;
3
using System.Text;
4
using System.Web.UI;
5
using System.ComponentModel;
6
7
namespace buttonControl
8

{
9
// 继承Control,IPostBackEventHandler
10
public class myButton: Control,IPostBackEventHandler
11
{
12
protected event EventHandler Click;
13
14
protected virtual void OnClick(EventArgs e)
15
{
16
if (Click != null)
17
{
18
Click(this, e);// 调用事件代理
19
}
20
}
21
22
// 首先触发RaisePostBackEvent事件
23
public void RaisePostBackEvent(string eventArgs)
24
{
25
// EventArgs.Empty相当于new EventArgs(),代表没有事件数据。
26
OnClick(EventArgs.Empty);
27
}
28
29
protected override void Render(HtmlTextWriter writer)
30
{
31
// 为元素定义UniqueID,为了与IPostBackEventHandler服务器控件的UniqueID相对应
32
writer.Write("<input type='submit' name='" + this.UniqueID + "' value='提交'/>");
33
34
base.Render(writer);
35
}
36
}
37
}
38
在Web应用程序中添加对该类库的引用,
在页面中注册
<%@ Register assembly="buttonControl" namespace="buttonControl" tagprefix="cc2" %>
引用自定义的button控件
<cc2:myButton ID="MyButton1" runat="server" onclick="MyButton1_Click">
</cc2:myButton>
后台测试:
protected void MyButton1_Click(object sender, EventArgs e)
{
Response.Write("这是我自定义的按钮控件的单击事件");
}
如果在页面上多次调用该控件,编译器就会为每个事件委托实例生成一个字段,
如果事件很多,则一个委托一个字段的方式看起来很浪费系统资源,
可以采用EventHandlerList来优化。把类库项目buttonControl改为

Code
1
using System;
2
using System.Web;
3
using System.Text;
4
using System.Web.UI;
5
using System.ComponentModel;
6
7
namespace buttonControl
8

{
9
// 继承Control,IPostBackEventHandler
10
public class myButton: Control,IPostBackEventHandler
11
{
12
13
// 把事件定义成私有静态属性
14
public static readonly object ClickKey = new object();
15
16
// 将事件定义为属性,get set用add和remove代替。
17
public event EventHandler Click
18
{
19
add
{ Events.AddHandler(ClickKey, value); }
20
remove
{ Events.RemoveHandler(ClickKey, value); }
21
}
22
23
protected void OnClick(EventArgs e)
24
{
25
EventHandler onclickEventDelegate = (EventHandler)Events[ClickKey];
26
27
if (onclickEventDelegate != null)
28
{
29
onclickEventDelegate(this, e);
30
}
31
}
32
33
public void RaisePostBackEvent(string eventArgs)
34
{
35
OnClick(EventArgs.Empty);
36
}
37
38
protected override void Render(HtmlTextWriter writer)
39
{
40
// 为元素定义UniqueID,为了与IPostBackEventHandler服务器控件的UniqueID相对应
41
writer.Write("<input type='submit' name='" + this.UniqueID + "' value='提交'/>");
42
43
base.Render(writer);
44
}
45
}
46
}
47