Tip of the Day – Routed Events

Source Code

A routed event is is bubbled up the user interface tree whether or not it is handled by the object that receives the event. For example, if we return to a previous example in which we had a button within which were three sub-controls, the middle of which was a stack panel containing a  check box whose content had another stack panel with two buttons, the first of which itself had content which was an html button…

OneBusyButton

you can see that we want to be able to click on the radio button within the check box that is within the button and yet still have the click event bubble up and click the button. Yet, at the same time, we may want to respond to the click on the radio button or the check box being clicked. We saw the XAML for creating this control previously so there is no need to review that. It will be unchanged except that  we'll want to add just one control for this example, and that is a list box that can hold messages indicating which control has registered the mouse down event,

MessageListBox

Note that to accommodate this helpful list box we need to add a row and a column to the grid, which is easily accomplished in our row and grid definitions at the top of the file,

NewRowAndColumn

With that in place, we need only create event handlers to see how the events "bubble up" even as they are handled.

BubblingEventHandlers

Each of these event handlers is implemented to add a notice to the list box we added in the third column,

image

If you click on an outer object (such as the check box border, only one event fires,

OneEventFired

Whereas if you click on an inner object (e.g., a radio button, you can see that the event is routed to the outer (containing) objects for handling as well.

clickonRadioButton

In this image, the user has clicked on the inner radio button. Because MouseLeftDown is a routed event, the event bubbles up through the UI tree, from the radio button to the check box to the surrounding border (and on up through the other surrounding UI elements that don't have event handlers!)

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in z Silverlight Archives. Bookmark the permalink.