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

Advertisement

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: