将子控件的点击事件传递给父控件 [英] Pass click event of child control to the parent control

查看:70
本文介绍了将子控件的点击事件传递给父控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Windows 窗体,它有一个窗格,其中包含从 Windows 窗体派生的另一个类.这作为窗格中的控件包含.它本身包含两个按钮.

I have a Windows form, having a pane, which contains another class, derived from Windows Forms. This is contained as a control within the pane. It contains two buttons within itself.

我希望子控件的事件一直传递到父窗口.例如,窗格中的子窗口有一个 Cancel 按钮,应该关闭它.我希望父控件,即主窗口也关闭,但是如何拦截子控件的按钮点击事件?

I'd like the events of the child control to be passed all the way to the parent window. For example, the child window in the pane has a Cancel button, which is supposed to close it. I'd like the parent control, i.e., the main window to close as well, but how can I intercept the button click event of the child control?

我可以修改子控件,但只有在没有其他方式以适当的方式实现这一点的情况下,我宁愿避免它.

I can modify the child control, but only if there is no other way to achieve this in a proper way, I'd rather like to avoid it.

推荐答案

虽然你可以直接从 child 与 parent form 交互,但最好通过 child control 引发一些事件并订阅 parent form 中的事件.

While you can interact with parent form directly from child, It's better to raise some events by child control and subscribe for the events in parent form.

从孩子那里引发事件:

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的原因就是为了遵循模式让派生者重写方法并自定义引发事件之前/之后的行为.

Note: To raise the XXXX event, that's enough to invoke the XXXX event delegate; the reason of creating the protected virtual OnXXXX is just to follow the pattern to let the derivers override the method and customize the behavior before/after raising the event.

在父级中订阅和使用事件:

//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();
}

要了解有关活动的更多信息,请查看:

To learn more about events, take a look at:

这篇关于将子控件的点击事件传递给父控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆