Pages

Friday, January 27, 2012

C# Event Handler / Delegates

My Notes:

Publishing Events:
Must determine what information to pass to an event within an EventArgs parameter.
Create a custom class that derives from EventArgs.

public class MyEventArgs : EventArgs
{
    public string myName { get; set; }
    public string newName { get; set; }
    public bool cancel { get; set; }
}

A custom class doesn’t have to be created. Any built-in types, which derive from EventArgs can be used, e.g. RoutedEventArgs.
.After creating a custom EventArgs class or using a built-in type deriving from EventArgs, create a public delegate.

Delegates

Delegates are similar to C pointers that reference methods from other classes.

public delegate void NameEventHandler(object sender, EventArgs e);

Above delegate expects to reference methods that return void and passes an object and an EventArgs type. These are considered the signature, and the signature is with any method, which the delegate references.

Examples:

public delegate void BtnClickEventHandler(object sender, RoutedEventArgs e);
 
private delegate bool MyEventHandler(object sender, MyEventArgs e);

  • A delegate is an anonymous function.
  • A delegate’s name can be named anything.
  • Delegates have an invocation list
  • Methods with exact signature can be added to a delegate’s invocation list, which all methods add will be raised.
Events

An event manages delegates and are type safe. Events manages adding and removing of delegates. Only methods added to an invocation list can only be removed by who added it to the list.

Events are Public
public event BtnClickEventHandler BtnClick;
 
public event MyEventHandler My;


Create a Helper Function

Create a method with a signature matching the preferred delegate.

public void OnMy(string name, string newName) 
{
//Reference a new MyEventArgs 
 
MyEventArgs myEvtArgs = new MyEventArgs();
 
myEvtArgs.myName = name;
myEvtArgs.newName = newName;
myEvtArgs.cancel = false;
 
My(this, myEvtArgs);  //Raise the event
 
}




Top to Bottom

private class MyEventArgs : EventArgs
 {
     public string myName { get; set; }
     public string newName { get; set; }
     public bool cancel { get; set; }
 }
 
 private delegate void MyEventHandler(object sender, MyEventArgs e);
 public event MyEventHandler My;
 
 public void OnMy(string name, string newName)
 {
     if (My != null)  //Insure someone is handling the event
     {
         MyEventArgs evtArgs = new MyEventArgs();
         evtArgs.myName = name;
         evtArgs.newName = newName;
         evtArgs.cancel = false;
 
         My(this, evtArgs);
     }
 }
 public MainWindow()
 {
     OnMy("Kirk", "Tom");
 }









No comments:

Post a Comment