UserControl上的公共自定义事件

时间:2013-02-21 08:41:05

标签: c# .net winforms events event-handling

我想要这个:

public partial class ucTest : UserControl  
{
...  
SomeEvent { MessageBox.Show("Inner Call") }
}


public partial class frmTest: Form
{
...  
SomeEvent += OuterEventInstance;
...
void OuterEventInstance(object sender, EventArgs e)
{ MessageBox.Show("Inner Call") }
... 
}

如何在包含此用户控件实例的表单中定义可用(和可扩展)的用户控件上的公共事件?

1 个答案:

答案 0 :(得分:2)

这样的事情:

public partial class ucTest : UserControl  
{
   public event  EventHandler SomeEvent;

   private void OnSomeEvent()
   {
        EventHandler handler = SomeEvent;
        if(handler != null)
             handler(this, EventArgs.Empty);
   } 

}


public partial class frmTest: Form
{
    public frmTest()
    {
        ucTest uc = new ucTest(); 
        uc.SomeEvent += OuterEventInstance;
    }

    //...

    void OuterEventInstance(object sender, EventArgs e)
    {
        MessageBox.Show("Inner Call")
        //...
    }
}