一個有Onclick事件的button例子:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.ComponentModel;
namespace ComponentControl
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:MyButton runat=server></{0}:MyButton>")]
public class Ctrl4 : Control, IPostBackEventHandler
{
public event EventHandler Click;//定義事件,EventHandler為系統委託名
IPostBackEventHandler 成員IPostBackEventHandler 成員IPostBackEventHandler 成員#region IPostBackEventHandler 成員
//該方法用於註冊事件
public void RaisePostBackEvent(string eventArgument)
{
if (Click != null)
{
Click(this, EventArgs.Empty); //實現委託方法
}
}
#endregion
public string Text //設定屬性Text的值
{
get { return ViewState["text"] == null ? "Button" : ViewState["text"].ToString(); }
set { ViewState["text"] = value; }
}
protected override void Render(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Type, "Submit");
writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); //跟下面一句代碼實現同樣效果,觸發伺服器端事件,屬性必須是Name,不能為ID
//writer.AddAttribute(HtmlTextWriterAttribute.Onclick, Page.GetPostBackEventReference(this));
writer.AddAttribute(HtmlTextWriterAttribute.Value, Text);
writer.RenderBeginTag(HtmlTextWriterTag.Input);
writer.RenderEndTag();
//writer.Write("<INPUT TYPE=submit name=" + this.UniqueID +" Value='Button' />");
}
}
}
另外一種最佳化的事件實現
EventHandlerList 類提供一個簡單的委託列表來添加和刪除委託,下面來看看更改後的代碼,
AddHandler有兩個參數事件對象和添加的委託,在OnClick事件中必須顯示將委託轉換為EventHandler類型
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
namespace ComponentControl
{
public class Ctrl5:Control,IPostBackEventHandler
{
// 聲明Click事件委託
private static readonly object obj = new object();
public virtual event EventHandler Click
{
add {
Events.AddHandler(obj, value);
}
remove
{
Events.RemoveHandler(obj, value);
}
}
protected override void Render(HtmlTextWriter writer)
{
writer.Write("<input type=submit name="+this.UniqueID+" value=Button />");
}
IPostBackEventHandler 成員IPostBackEventHandler 成員#region IPostBackEventHandler 成員
public void RaisePostBackEvent(string eventArgument)
{
EventHandler child = (EventHandler)Events[obj];
if (child != null)
child(this, EventArgs.Empty);
}
#endregion
}
}