Winforms用户控制自定义事件

Kev*_*vin 21 .net c# user-controls event-handling winforms

有没有办法提供用户控件自定义事件,并在用户控件中的事件上调用事件.(我不确定调用是否是正确的术语)

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


    private void TextBox_Validated(object sender, EventArgs e)
    {
        // invoke UserControl event here
    }
}
Run Code Online (Sandbox Code Playgroud)

和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
    }
}
Run Code Online (Sandbox Code Playgroud)

Ed *_* S. 30

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

class MyUserControl : UserControl
{
   public event EventHandler TextBoxValidated
   {
      add { textBox1.Validated += value; }
      remove { textBox1.Validated -= value; }
   }
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*ner 28

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的表格上:

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
    }
}
Run Code Online (Sandbox Code Playgroud)