Manage routed events in WPF

May include but is not limited to: tunneling vs. bubbling events, handling and cancelling events

OK, this is probably more interesting than building an animation, so let’s begin! I guess every one of us got this far is fairly familiar with events. They are everywhere (especially if you use ASP.NET WebForms); but what is that ugly routed word before them? It’s simpler than you might imagine first. A routed event is an event that can be catch and (or) handled on an element that didn’t fire it (but there should be some relation). Imagine a click to a button. You can handle that click on the button level, but if a button is inside a grid, and then you can handle the click on the grid level, or even at the window level. I used the word handle, but it’s a little misleading. It suggests that the event is finished, gone for good after you make it trigger some event handler. Now this is not necessarily the case, you can handle a routed event multiple times in multiple places.

The previous paragraph became too long, so I start a new one. There are two types of routed events (I think everything starts to have two types) tunneling events which goes down to the hierarchy (like any tunnel) and is start from the Window (or the topmost container). The other type is bubbling event, which goes up in the hierarchy like a bubble (but it’s not falling back sometimes).

You can handle routed events (making them stop wherever they are) by setting their Handled property to true. It worth looking at the RoutedEventArgs class (gone are the days of EventArgs!):

  • Source: the source of the routed event. You can interpret this property as an object which was the topmost when you clicked somewhere on your screen, or the element that had the keyboard input when you hit a key.
  • OriginalSource: usually the same as source, and indicates what had originally caused the event.
  • RoutedEvent: the event which triggered the handler.
  • Handled: a Boolean indicating whether or not mark the event as handled.

One last thing to say on routed events. There are an awful lot of events exposed by WPF elements. Usually they hunt in pairs, for example you have a KeyDown event for reacting to keyboard key pressing, and a PreviewKeyDown, which reacts to the exact same thing. And you can see a lot of other events with the Preview prefix. Now comes the magic rule: the ones with Preview are tunneling events, and the ones without it are bubbling events – just in case you ever wondered.

Leave a Reply

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

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s