[英]Pass click event of child control to the parent control
我有一個 Windows 窗體,它有一個窗格,其中包含從 Windows 窗體派生的另一個類。 這作為窗格中的控件包含。 它本身包含兩個按鈕。
我希望子控件的事件一直傳遞到父窗口。 例如,窗格中的子窗口有一個Cancel
按鈕,應該關閉它。 我希望父控件,即主窗口也關閉,但是如何攔截子控件的按鈕單擊事件?
我可以修改子控件,但只有在沒有其他方法以適當的方式實現這一點時,我才寧願避免它。
雖然您可以直接從子窗體與父窗體交互,但最好通過子控件引發一些事件並訂閱父窗體中的事件。
從 Child 引發事件:
public event EventHandler CloseButtonClicked;
protected virtual void OnCloseButtonClicked(EventArgs e)
{
CloseButtonClicked.Invoke(this, e);
}
private void CloseButton_Click(object sender, EventArgs e)
{
//While you can call `this.ParentForm.Close()` but it's better to raise the event
//Then handle the event in the form and call this.Close()
OnCloseButtonClicked(e);
}
注意:要引發 XXXX 事件,調用 XXXX 事件委托就足夠了; 創建protected virtual OnXXXX
的原因只是為了遵循模式讓派生者覆蓋該方法並在引發事件之前/之后自定義行為。
在 Parent 中訂閱和使用事件:
//Subscribe for event using designer or in constructor or form load
this.userControl11.CloseButtonClicked += userControl11_CloseButtonClicked;
//Close the form when you received the notification
private void userControl11_CloseButtonClicked(object sender, EventArgs e)
{
this.Close();
}
要了解有關事件的更多信息,請查看:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.