使用者控制項 (`UserControl.ascx`) 內含按鈕 `AButton`,點擊時需通知容器頁面執行特定邏輯。
public delegate void ClickEventHandler(object sender, EventArgs e);
public partial class MyUserControl : System.Web.UI.UserControl
{
protected System.Web.UI.WebControls.Button AButton;
// 1. 宣告事件
public event ClickEventHandler Click;
// 2. 引發事件的保護方法
protected virtual void OnClick(EventArgs e)
{
Click?.Invoke(this, e); // C# 6.0+ 語法,舊版需判斷 Click != null
}
// 3. 按鈕點擊事件處理
private void AButton_Click(object sender, System.EventArgs e)
{
this.OnClick(e); // 觸發自訂事件
}
}
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
// 4. 尋找控制項並訂閱事件
MyUserControl uc = this.FindControl("myUserControlID") as MyUserControl;
if (uc != null)
uc.Click += new ClickEventHandler(this.UserControl_Clicked);
}
private void UserControl_Clicked(object sender, System.EventArgs e)
{
// 5. 處理來自使用者控制項的事件
Response.Write("收到 UserControl 事件!");
}
<%@ Register Src="UserControl.ascx" TagPrefix="uc" TagName="MyControl" %>
<uc:MyControl ID="myUserControlID" runat="server" />
public class MyEventArgs : EventArgs
{
public string CustomData { get; set; }
}
public delegate void CustomClickHandler(object sender, MyEventArgs e);
// 控制項端
public event CustomClickHandler CustomClick;
protected virtual void OnCustomClick(MyEventArgs e) => CustomClick?.Invoke(this, e);
private void AButton_Click(object sender, EventArgs e) => OnCustomClick(new MyEventArgs { CustomData = "來自控制項的資料" });
// 頁面端
uc.CustomClick += (s, e) => { Response.Write(e.CustomData); };
這就是手工實作「觀察者模式」。掌握此技巧,即可打破 UserControl 與 Page 的耦合,實現真正的元件化開發。