且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在用户控件中创建事件并在主窗体中处理它?

更新时间:2023-12-06 12:11:22

您需要为用户控件创建事件处理程序,该事件处理程序在用户内部发生事件时引发控制被解雇。这将使您能够在事件链上冒泡,以便可以从表单中处理事件。

You need to create an event handler for the user control that is raised when an event from within the user control is fired. This will allow you to bubble the event up the chain so you can handle the event from the form.

在UserControl上单击 Button1 时,我将触发 Button1_Click 会触发 UserControl_ButtonClick 形式:

When clicking Button1 on the UserControl, i'll fire Button1_Click which triggers UserControl_ButtonClick on the form:

用户控件:

[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代替 if(this.ButtonClick!= null)this.ButtonClick(this,e); .invoke(this,e); ,其功能基本相同,但更短。

  • Newer Visual Studio versions suggest that instead of if (this.ButtonClick!= null) this.ButtonClick(this, e); you can use ButtonClick?.Invoke(this, e);, which does essentially the same, but is shorter.

Browsable 属性使事件在Visual Studio的设计器(事件视图)中可见,类别将其显示在操作类别中,而说明提供了对其的描述。您可以完全省略这些属性,但是由于VS可以为您处理,因此可以让设计者轻松使用。

The Browsable attribute makes the event visible in Visual Studio's designer (events view), Category shows it in the "Action" category, and Description provides a description for it. You can omit these attributes completely, but making it available to the designer it is much more comfortable, since VS handles it for you.