#595 – Syntax Choices for Defining an Event Handler

There are several different syntaxes that you can use when specifying an event handler in code.  (This is assuming that you’re using a CLR event wrapper, rather than calling UIElement.AddHandler directly).

The most common syntax for defining an event handler is to declare a new instance of the appropriate handler type, passing it the name of a preexisting method.  Since the handler type is a delegate, you’re passing the name of a method to the delegate’s constructor.

myButton.Click += new RoutedEventHandler(myButton_Click);
myTextBox.KeyDown += new KeyEventHandler(myTextBox_KeyDown);

As a shortcut, you can just use the name of the method (your handler).

myButton.Click += myButton_Click;
myTextBox.KeyDown += myTextBox_KeyDown;

Instead of defining a separate method, you can just specify an anonymous method, with or without arguments.

            myButton.Click += delegate { Trace.WriteLine("Hey, you clicked a button"); };
            myTextBox.KeyDown += delegate(object sender, KeyEventArgs e) { Trace.WriteLine(string.Format("sender: {0}", sender)); };
Advertisement

#594 – Routed Events Under the Covers

Traditional CLR events are basically a wrapper around a private instance of a multicast delegate type.  When you add an event handler using the += operator, your handler gets added to the delegate’s invocation list.

// CLR event under the covers
private EventHandler barked;
public event EventHandler Barked
{
    add { barked += value; }
    remove { barked -= value; }
}

Routed events in WPF look like standard CLR events because they are exposed via a CLR event.  But they are implemented differently.

When you use += for a routed event, the UIElement.AddHandler method is called.

    // From ButtonBase.cs
    public static readonly RoutedEvent ClickEvent;
    public event RoutedEventHandler Click { add { AddHandler(ClickEvent, value); } remove { RemoveHandler(ClickEvent, value); } }

The AddHandler method adds information about both the event and the handler to list of event handlers that is stored within the UIElement, used when the event is raised.