How to create Routed Events in WPF

HelloSmile. Today I’m going to show you how to create routed events in WPF. In case you forgot or don’t know about routed events read this article.

In few words, routed events are events that can either bubble up or go down through element tree.

Here is code which creates routed event:

public static readonly RoutedEvent SubmittionCompletedEvent = EventManager.RegisterRoutedEvent( "SubmittionCompleted", RoutingStrategy.Bubble, typeof (RoutedEventHandler), typeof (MainWindow)); public event RoutedEventHandler SubmittionCompleted { add { AddHandler(SubmittionCompletedEvent, value); } remove { RemoveHandler(SubmittionCompletedEvent, value); } }

Routed events are similar to Dependency Properties in their creation. As you can see, I use static RegisterRoutedEvent method of EventManager class which takes arguments which define event name, routing strategy, type of delegate, type of event owner and returns an instance of RoutedEvent class.

Later this returned instance is saved in static field which has name according to convention: “event name” + “event” suffix (e.g. MouseDownEvent). In order to register or deregister listener for this event, normal CLR event is provided which uses AddHandler and RemoveHandler to attach or detach handler respectively.

I think that idea of events that can bubble up or tunnel down is very useful approach for building flexible applications that allow low-level components to send notifications to high level components without explicit events re-throwing at each level.