将子控件的点击事件传递给父控件
Pass click event of child control to the parent control
我有一个 Windows 表单,有一个窗格,其中包含另一个 class,派生自 Windows 表单。这作为控件包含在窗格中。它本身包含两个按钮。
我希望将子控件的事件一直传递给父控件 window。例如,窗格中的子 window 有一个 Cancel
按钮,应该关闭它。我想关闭父控件,即主要 window 也关闭,但是如何拦截子控件的按钮单击事件?
我可以修改子控件,但前提是没有其他方法以适当的方式实现此目的,我宁愿避免它。
虽然您可以直接从 child 与 parent 表单交互,但最好通过 child 控件引发一些事件并订阅 parent 表单中的事件。
从 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
的原因只是为了遵循模式让派生者覆盖方法并自定义引发事件的行为 before/after。
订阅并使用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();
}
要了解有关活动的更多信息,请查看:
我有一个 Windows 表单,有一个窗格,其中包含另一个 class,派生自 Windows 表单。这作为控件包含在窗格中。它本身包含两个按钮。
我希望将子控件的事件一直传递给父控件 window。例如,窗格中的子 window 有一个 Cancel
按钮,应该关闭它。我想关闭父控件,即主要 window 也关闭,但是如何拦截子控件的按钮单击事件?
我可以修改子控件,但前提是没有其他方法以适当的方式实现此目的,我宁愿避免它。
虽然您可以直接从 child 与 parent 表单交互,但最好通过 child 控件引发一些事件并订阅 parent 表单中的事件。
从 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
的原因只是为了遵循模式让派生者覆盖方法并自定义引发事件的行为 before/after。
订阅并使用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();
}
要了解有关活动的更多信息,请查看: