Winforms用户控件自定义事件

23

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

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


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

还有主窗体(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
    }
}

你可能会发现这个问题的第一个答案很有用 https://dev59.com/IkvSa4cB1Zd3GeqPfpvD - John Knoeller
可能是 https://dev59.com/m2sz5IYBdhLWcg3weHkA 的重复问题。 - Arun Prasad
2个回答

33

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

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

30

我认为您想要的是这样的:

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);
    }
}

然后在您的表单上:

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
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接