C# 将子控件的单击事件传递给父控件
我有一个Windows窗体,有一个窗格,其中包含从Windows窗体派生的另一个类。这是作为窗格中的控件包含的。它本身包含两个按钮 我希望子控件的事件一直传递到父窗口。例如,窗格中的子窗口有一个C# 将子控件的单击事件传递给父控件,c#,.net,winforms,user-controls,controls,C#,.net,Winforms,User Controls,Controls,我有一个Windows窗体,有一个窗格,其中包含从Windows窗体派生的另一个类。这是作为窗格中的控件包含的。它本身包含两个按钮 我希望子控件的事件一直传递到父窗口。例如,窗格中的子窗口有一个Cancel按钮,用于关闭它。我希望父控件(即主窗口)也关闭,但如何截获子控件的按钮单击事件 我可以修改子控件,但只有在没有其他方法以适当方式实现这一点的情况下,我才希望避免它。虽然您可以直接从子控件与父窗体交互,但最好通过子控件引发一些事件并订阅父窗体中的事件 从子级引发事件: public event
Cancel
按钮,用于关闭它。我希望父控件(即主窗口)也关闭,但如何截获子控件的按钮单击事件
我可以修改子控件,但只有在没有其他方法以适当方式实现这一点的情况下,我才希望避免它。虽然您可以直接从子控件与父窗体交互,但最好通过子控件引发一些事件并订阅父窗体中的事件 从子级引发事件:
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);
}
//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();
}
注意:要引发XXXX事件,足以调用XXXX事件委托;创建受保护的虚拟OnXXXX
的原因只是为了遵循该模式,让派生程序覆盖该方法,并在引发事件之前/之后自定义行为
订阅并使用父级中的事件:
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);
}
//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();
}
要了解有关活动的更多信息,请查看:
CloseButton\u Click
分配给CloseButton
的Click
事件;private void btnOK_Click(object sender,EventArgs e){CloseButtonClicked?.Invoke(this,e);}@ClausMøllerJørgensen感谢您的反馈,是的,我们可以,特别是这部分CloseButtonClicked?.Invoke(this,e)代码>但是。。。单击一次关闭按钮是有原因的。遵循.NET的标准事件模式,也让开发人员有机会重写虚拟的OnCloseButtonClicked
方法。