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

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

问题描述

我有一个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.

推荐答案

虽然您可以直接从子级与父级表单进行交互,但最好通过子级控制引发一些事件并以父级表单订阅事件。

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.

Raise event来自孩子:

Raise event from Child:

public event EventHandler CloseButtonClicked;
protected virtual void OnCloseButtonClicked(EventArgs e)
{
    var handler = CloseButtonClicked;
    if (handler != null)
        handler(this, e);
}
private void CloseButton_Click(object sender, EventArgs e)
{
    //While you can call `this.ParentForm.Close()` it's better to raise an event
    OnCloseButtonClicked(e);
}

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

Subscribe and use event in Parent:

//Subscribe for event using designer or in 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:

  • Handling and raising events
  • Standard .NET event pattern

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

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