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

How do I make an Event in the Usercontrol and have it handled in the Main Form?(如何在用户控件中创建一个事件并在主窗体中处理它?)

本文介绍了如何在用户控件中创建一个事件并在主窗体中处理它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的用户控件,我想做一些相对简单的事情.

I have a custom usercontrol and I want to do something relatively simple.

当该用户控件的值发生变化时,让主窗体更新显示窗口.

When ever a numeric up down in that usercontrol's value changes, have the main form update a display window.

如果 NUD 不在用户控件中,这不是问题,但我似乎无法弄清楚如何让主窗体而不是用户控件处理事件.

This is not a problem if the NUD was not in a usercontrol but I can't seem to figure out how to have the event handled by the mainform and not the usercontrol.

推荐答案

您需要为用户控件创建一个事件处理程序,当用户控件内的事件被触发时引发.这将允许您将事件沿链向上冒泡,以便您可以处理表单中的事件.

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 版本建议您可以使用 if (this.ButtonClick!= null) this.ButtonClick(this, e); 而不是 ButtonClick?.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 的设计器(事件视图)中可见,Category 将其显示在Action"类别中,描述 为其提供描述.您可以完全省略这些属性,但将其提供给设计人员会更舒服,因为 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.

这篇关于如何在用户控件中创建一个事件并在主窗体中处理它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在用户控件中创建一个事件并在主窗体中处理它?

基础教程推荐