將事件向上傳遞到使用者控制項層次結構
在自訂使用者控制項中,通常希望讓控制項中引發的事件可供主控件存取形式。當嘗試處理源自子控制項的事件(例如數字上下控制項中的值變更)時,這一點變得很明顯。
建立事件處理程序
要解決此問題挑戰,在使用者控制項中建立事件處理程序,當所需事件發生時觸發該事件處理程序。此事件處理程序應將事件「冒泡」到表單,使其能夠處理該事件。
範例程式碼
考慮一個有名為「Button1」的按鈕的使用者控制項":
用戶控:
[Browsable(true)] [Category("Action")] [Description("Invoked when user clicks button")] public event EventHandler ButtonClick; protected void Button1_Click(object sender, EventArgs e) { //bubble the event up to the parent if (this.ButtonClick!= null) this.ButtonClick(this, e); }
主要形式:
UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick); protected void UserControl_ButtonClick(object sender, EventArgs e) { //handle the event }
註
以上是如何將事件從使用者控制項傳遞到其父窗體?的詳細內容。更多資訊請關注PHP中文網其他相關文章!