首頁 > 後端開發 > C++ > 如何將事件從使用者控制項傳遞到其父窗體?

如何將事件從使用者控制項傳遞到其父窗體?

Barbara Streisand
發布: 2025-01-05 20:35:39
原創
606 人瀏覽過

How Can I Pass Events from a User Control to Its Parent Form?

將事件向上傳遞到使用者控制項層次結構

在自訂使用者控制項中,通常希望讓控制項中引發的事件可供主控件存取形式。當嘗試處理源自子控制項的事件(例如數字上下控制項中的值變更)時,這一點變得很明顯。

建立事件處理程序

要解決此問題挑戰,在使用者控制項中建立事件處理程序,當所需事件發生時觸發該事件處理程序。此事件處理程序應將事件「冒泡」到表單,使其能夠處理該事件。

範例程式碼

考慮一個有名為「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 
}
登入後複製

  • 事件可見度Browsable 屬性公開Visual Studio 設計器的「事件」中的事件檢視。 🎜>事件描述: 描述屬性提供事件的簡要描述。 >
  • 事件處理省略:
  • 可以省略上述屬性,但設計器可用性增強可用性。 :ButtonClick?.Invoke(this, e);而不是if (this.ButtonClick!= null) this.ButtonClick(this, e);.

以上是如何將事件從使用者控制項傳遞到其父窗體?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板