的WinForms用户控件自定义事件 [英] Winforms user controls custom events

查看:162
本文介绍了的WinForms用户控件自定义事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法给一个用户控件自定义事件,并在用户控件内的事件调用事件。 (我不知道,如果是调用正确的术语)

 公共部分类示例:用户控件
{
样品公()
{
的InitializeComponent();
}


私人无效TextBox_Validated(对象发件人,EventArgs五)
{
//调用用户控件的事件在这里
}
}

而MainForm的:

 公共部分类的MainForm:表格
{
样品的私人= sampleUserControl样品新();

公众的MainForm()
{
this.InitializeComponent();
sampleUserControl.Click + =新的EventHandler(this.CustomEvent_Handler);
}
私人无效CustomEvent_Handler(对象发件人,EventArgs五)
{
//做的东西
}
}


解决方案

除此之外史蒂夫张贴的例子,也有语法,可它可以简单地传递事件通过。这类似于创建一个属性:

 类的MyUserControl:用户控件
{
公共事件的EventHandler TextBoxValidated
{
加{textBox1.Validated + =价值; }
拆下{textBox1.Validated - =价值; }
}
}


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)

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

解决方案

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:

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

这篇关于的WinForms用户控件自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆