繁体   English   中英

Winforms用户控制自定义事件

[英]Winforms user controls custom events

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM