Wednesday 8 July 2015

Raise an event in a user control and catch it in main window. ( Custom Events, EventArgs and Event Broker )



In this article, Will try to explain how to hook a custom event to an object.  In bit advanced and also create own event arguments that are derived from the EventArgs base class.

Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.

Declare event using EventHandler<T> where T is your class that derives from EventArgs:
Different thread

Now take a look into our custom event class:


Class Name : SetHeaderLabelEventArgs

public class SetHeaderLabelEventArgs : EventArgs
{
            public SetHeaderLabelEventArgs(string displayString)
            {
                this.DisplayString = displayString;
            }

            public string DisplayString { get; set; }
}



Event Broker Class 

public static class EventBroker
{
  public static event EventHandler LabelSet; 
  public static void SetHeaderLabel(object sender, {Namespace}.SetHeaderLabelEventArgs e)
  {
    if (LabelSet != null)
       LabelSet(sender, e);
  } 
}



Finally, here it is the object:

Calling Event form One User Control to Event Broker
 
public partial class ucStudent : UserControl
    {
      private void button1_Click(object sender, EventArgs e)
      {

          string displayString = "Header Label";

Namespace.SetHeaderLabelEventArgs args = new    Namespace.SetHeaderLabelEventArgs(displayString);
            EventBroker.SetHeaderLabel(this, args);
    }
}



Main window is listening to Event Broker
public partial class MainWindow : Window
    {
public MainWindow ()
       {
EventBroker.LabelSet -= EventBroker_SetHeader;
EventBroker.LabelSet += EventBroker_SetHeader;
}


private void EventBroker_SetHeader(object userControlName, EventArgs e)
{
Namespace.SetHeaderLabelEventArgs args = (Namespace.SetHeaderLabelEventArgs)e;
MessageBox.Show(args.DisplayString);
}

}


No comments:

Post a Comment