Input with Windows Presentation Foundation - Halting Event Routing
(Page 3 of 4 )
There are some situations in which you might not want events to bubble up. For example, you may wish to convert the event into something else—the Button element effectively converts aMouseDownevent followed by aMouseUpevent into a singleClick event. It suppresses the more primitive mouse button events so that only theClickevent bubbles up out of the control. (This is why the event bubbling stopped at the button in the previous example.)
Any handler can prevent further processing of a routed event by setting theHandledproperty of theRoutedEventArgs, as shown in Example4-3.
Example 4-3. Halting event routing with Handled
void ButtonDownCanvas(object sender, RoutedEventArgs e) {
Debug.WriteLine("ButtonDownCanvas");
e.Handled = true;
}
If you set theHandled flag in aPreviewhandler, not only will the tunneling of thePreviewevent stop, but also the corresponding bubbling event that would normally follow will not be raised at all. This provides a way of stopping the normal handling of an event.
Determining the Target
Although it is convenient to be able to handle events from a group of elements in a single place, your handler might need to know which element caused the event to be raised. You might think that this is the purpose of the sender parameter of your handler. In fact, thesenderalways refers to the object to which you attached the event handler. In the case of bubbled and tunneled events, this often isn’t the element that caused the event to be raised. In Example 4-1, the MouseDownGridhandler’ssender will always be theGriditself, regardless of which element in the grid was clicked.
Fortunately, it’s easy to find out which element was the underlying cause of the event. The handler has aRoutedEventArgsparameter, which offers aSource property for this purpose. This is particularly useful if you need to handle events from several different sources in the same way. For example, suppose you create a window that contains a number of graphical elements, and you’d like each to change shape when clicked. Instead of attaching aMouseDownevent handler to each individual shape, you could attach a single handler to the window. All the events would bubble up from any shape to this single handler, and you could use theSourceproperty to work out which shape you need to change. (Shapes are discussed in Chapter 13. Example 13-5 uses exactly this trick.)
Next: Routed Events and Normal Events >>
More .NET Articles
More By O'Reilly Media
|
This article is excerpted from Programming WPF, Second Edition, written by Chris Sells and Ian Griffiths (O'Reilly, 2007; ISBN: 0596510373). Check it out today at your favorite bookstore. Buy this book now.
|
|