Routed Event Viewer

Understanding the order in which routed event handlers are invoked is an important WPF programming concept.

I wrote the below demonstration program as a visual aid for my WPF presentations and wanted to share it. It allows the user to select which routed event handlers to handle, which event handler will mark the routed event as handled and simulates code running in the handler.  If you have not read the MSDN topic “Routed Events Overview” I strongly suggest that you do.  Microsoft did an excellent job with the routed event documentation.

Routed Event Viewer

Running The Program

For your first run of the program, just press the Start Demo button and watch as the PreviewGenerateTrace routed event tunnels down the element tree and then the GenerateTrace bubbles up. As the each event handler is invoked, the viewer on the right (not pictured above) will be populated with the object type and routing strategy.

The CheckBoxes allow you to add event handlers for their associated object.

The RadioButtons allow you to designate which handler will mark the routed event as Handled. If the tunneling routed event PreviewGenerateTrace is Handled, the bubbling routed event GenerateTrace will not be raised. Once a routed event is marked as Handled, the remaining event handlers will still be invoked but their progress bars will be colored red to indicate that the routed event was previously Handled.

Class Handlers

For most readers of this post, the tunneling and bubbling of a routed event through the element tree will not be new information. However class handler might be.

Let’s start with a bubbling event first.  The MSDN documentation states, Class handlers are invoked before any instance listener handlers for an instance of that class, when that event reaches an element in its route. This can be seen in the above image, the bubbling Class handler gets invoked before any of the instance handlers.

This is true for the tunneling handlers also.  The tunneling class handler gets invoked before the instance handler of the Button that raised the event.

When I first read the documentation, I thought that the tunneling Class handler got called before any other tunneling event handlers, I was wrong.

Project

Download project source here.  After downloading, you MUST change the extension from .doc to .zip.

There are actually some pretty cool things going on within the program.  Getting the animations to process in the order the events actually got raised took some thinking.  After running the program but before diving into the code, think how you might program this.

Hope you like the program.

Just a grain of sand on the worlds beaches.

Comments are closed.

Follow

Get every new post delivered to your Inbox.

Join 241 other followers