C# Winforms 用户控件自定义事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2188059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:13:02  来源:igfitidea点击:

Winforms user controls custom events

c#.netwinformsuser-controlsevent-handling

提问by Kevin

Is there a way to give a User Control custom events, and invoke the event on a event within the user control. (I'm not sure if invoke is the correct term)

有没有办法给用户控件自定义事件,并在用户控件内的事件上调用该事件。(我不确定 invoke 是否正确)

public partial class Sample: UserControl
{
    public Sample()
    {
        InitializeComponent();
    }


    private void TextBox_Validated(object sender, EventArgs e)
    {
        // invoke UserControl event here
    }
}

And the MainForm:

和主窗体:

public partial class MainForm : Form
{
    private Sample sampleUserControl = new Sample();

    public MainForm()
    {
        this.InitializeComponent();
        sampleUserControl.Click += new EventHandler(this.CustomEvent_Handler);
    }
    private void CustomEvent_Handler(object sender, EventArgs e)
    {
        // do stuff
    }
}

采纳答案by Ed S.

Aside from the example that Steve posted, there is also syntax available which can simply pass the event through. It is similar to creating a property:

除了 Steve 发布的示例之外,还有可用的语法可以简单地传递事件。它类似于创建一个属性:

class MyUserControl : UserControl
{
   public event EventHandler TextBoxValidated
   {
      add { textBox1.Validated += value; }
      remove { textBox1.Validated -= value; }
   }
}

回答by Steve Danner

I believe what you want is something like this:

我相信你想要的是这样的:

public partial class Sample: UserControl
{
    public event EventHandler TextboxValidated;

    public Sample()
    {
        InitializeComponent();
    }


    private void TextBox_Validated(object sender, EventArgs e)
    {
        // invoke UserControl event here
        if (this.TextboxValidated != null) this.TextboxValidated(sender, e);
    }
}

And then on your form:

然后在你的表格上:

public partial class MainForm : Form
{
    private Sample sampleUserControl = new Sample();

    public MainForm()
    {
        this.InitializeComponent();
        sampleUserControl.TextboxValidated += new EventHandler(this.CustomEvent_Handler);
    }
    private void CustomEvent_Handler(object sender, EventArgs e)
    {
        // do stuff
    }
}