我有一个自定义用户控件,我想做一些相对简单的事情。
当该用户控件的值发生变化时,让主窗体更新显示窗口。
如果 NUD 不在用户控件中,这不是问题,但我似乎无法弄清楚如何让主窗体而不是用户控件处理事件。
最佳答案
您需要为用户控件创建一个事件处理程序,当用户控件中的事件被触发时将引发该事件处理程序。这将允许您将事件冒泡到链中,以便您可以处理表单中的事件。
当单击 UserControl 上的 Button1
时,我将触发 Button1_Click
,这将触发表单上的 UserControl_ButtonClick
:
用户控制:
[Browsable(true)] [Category("Action")]
[Description("Invoked when user clicks button")]
public event EventHandler ButtonClick;
protected void Button1_Click(object sender, EventArgs e)
{
//bubble the event up to the parent
if (this.ButtonClick!= null)
this.ButtonClick(this, e);
}
表格:
UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick);
protected void UserControl_ButtonClick(object sender, EventArgs e)
{
//handle the event
}
注意事项:
较新的 Visual Studio 版本建议您可以使用
ButtonClick?.Invoke( this, e);
,它的作用基本相同,但更短。Browsable
属性使事件在 Visual Studio 的设计器(事件 View )中可见,Category
将其显示在“Action”类别中,Description
为其提供描述。您可以完全省略这些属性,但让设计人员可以使用它会更舒服,因为 VS 会为您处理。
关于c# - 如何在用户控件中创建事件并在主窗体中处理它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7880850/