using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MSPress.ServerControls {
[
DefaultEvent("Click"),
DefaultProperty("Text")
]
public class SimpleLinkButton: WebControl, IPostBackEventHandler {
private static readonly object EventClick = new object(); //创建了一个只读的对象
[
Bindable(true),
Category("Behavior"),
DefaultValue(""),
Description("The text to display on the link")l
]
public virtual string Text {
get {
string s = (string)ViewState["Text"];
return((s == null) ? String.Empty : s);
}
set {
ViewState["Text"] = value;
}
}
protected override HtmlTextWriterTag TagKey {
get {
return HtmlTextWriterTag.A;
}
}
[
Category("Action"),
Description("Raised when the hyperlink is clicked")
]
public event EventHandler Click {
add {
Events.AddHandler(EventClick, value);
}
remove {
Events.RemoveHandler(EventClick, value);
}
}
void IPostBackEventHandler.RaisePostBackEvent(string eventArgument){
OnClick(EventArgs.Empty);
}
protected override void AddAttributesToRender(HtmlTextWriter writer) {
base.AddAttributesToRender(writer);
writer.AddAttribute(HtmlTextWriterAttribute.Href, Page.GetPostBackClientHyperlink(this, String.Empty));
}
protected virtual void OnClick(EventArgs e) {
EventHandler clickHandler = (EventHandler)Events[EventClick];
if (clickHandler != null) {
clickHandler(this, e);
}
}
protected override void Render(HtmlTextWriter writer) {
// Ensures that this control is nested in a server form.
if (Page != null) {
Page.VerifyRenderingInServerForm(this);
}
//base.Render(writer);调用基类Render方法,呈现基类的属性
base.Render(writer);
}
protected override void RenderContents(HtmlTextWriter writer) {
writer.Write(Text);
}
}
}
要理解的
protected static readonly object EventClick = new object();
public event EventHandler Click{
add {
Events.AddHandler(EventClick,value);
}
remove {
Events.RemoveHandler(EventClick,value);
}
}
在事件属性结构定义之前,首先需要定义Click事件委托对象。由于每个事件仅创建一次,因此,需要声明为静态和只读的。然后,在属性结构中通过AddHandler、RemoveHandler方法操作事件处理程序委托列表。当页面调用Click事件时,它向控件的EventHandlerList集合中添加或者删除处理程序。由于这种实现方法,在多个事件的声明过程中比普通的实现方法效率高,因此是非常值得推荐的方法。
另外,在OnClick方法的实现过程中,当用一个事件属性时,必须从EventHandlerList中取回委托,并将其转换成EventHandler的类型。
protected virtual void OnClick(EventArgs e){
EventHandler clickHandler = (EventHandler)Events[EventClick];
if(clickHandler != null) {
clickHandler(this,e);
}
}