2010-02-02 112 views
21

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

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

您可能会发现这第一个回答这个问题有用 http://stackoverflow.com/questions/2151049/net-custom-event-organization-assistance – 2010-02-03 00:20:56

回答

29

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

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

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

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

+1有帮助回答 – Kevin 2010-02-03 03:02:29

+0

太棒了。这个诀窍马上就没有任何问题了。 :) – Almo 2011-11-09 20:51:03