How do i raise an event in a usercontrol and catch it in mainpage?

梦想与她 提交于 2019-11-26 17:57:11

问题


I have a UserControl, and I need to notify the parent page that a button in the UserControl was clicked. How do I raise an event in the UserControl and catch it on the Main page? I tried using static, and many suggested me to go for events!


回答1:


Check out Event Bubbling -- http://msdn.microsoft.com/en-us/library/aa719644%28vs.71%29.aspx

Edit to add a quick example: (and additional edit to improve formatting)

User Control

public event EventHandler StatusUpdated;

private void FunctionThatRaisesEvent()
{
    //Null check makes sure the main page is attached to the event
    if (this.StatusUpdated != null)
       this.StatusUpdated(this, new EventArgs());
}

Main Page/Form

public void MyApp()
{
     //USERCONTROL = your control with the StatusUpdated event
     this.USERCONTROL.StatusUpdated += new EventHandler(MyEventHandlerFunction_StatusUpdated);
}

public void MyEventHandlerFunction_StatusUpdated(object sender, EventArgs e)
{
         //your code here
}



回答2:


Just add an event in your control:

public event EventHandler SomethingHappened;

and raise it when you want to notify the parent:

if(SomethingHappened != null) SomethingHappened(this, new EventArgs);

If you need custom EventArgs try EventHandler<T> instead with T beeing a type derived from EventArgs.




回答3:


Or if you are looking for a more decoupled solution you can use a messenger publisher / subscriber model such as MVVM Light Messenger here



来源:https://stackoverflow.com/questions/6192739/how-do-i-raise-an-event-in-a-usercontrol-and-catch-it-in-mainpage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!