#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.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment