Routed Events
Just as WPF adds more infrastructure on top of the simple notion of .NET properties, it also adds more infrastructure on top of the simple notion of .NET events. Routed events are events that are designed to work well with a tree of elements. When a routed event is raised, it can travel up or down the visual and logical tree, getting raised on each element in a simple and consistent fashion, without the need for any custom code.
Event routing helps most applications remain oblivious to details of the visual tree (which is good for restyling) and is crucial to the success of WPF's element composition. For example, Button exposes a Click event based on handling lower-level MouseLeftButtonDown and KeyDown events. When a user presses the left mouse button with the mouse pointer over a standard Button, however, they are really interacting with its ButtonChrome or TextBlock visual child. Because the event travels up the visual tree, the Button eventually sees the event and can handle it. Similarly, for the VCR-style Stop Button in the preceding chapter, a user might press the left mouse button directly over the Rectangle logical child. Because the event travels up the logical tree, the Button still sees the event and can handle it as well. (Yet if you really wish to distinguish between an event on the Rectangle versus the outer Button, you have the freedom to do so.)
Therefore, you can embed arbitrarily complex content inside an element like Button or give it an arbitrarily complex visual tree (using the techniques in Chapter 10), and a mouse left-click on any of the internal elements still results in a Click event raised by the parent Button. Without routed events, producers of the inner content or consumers of the Button would have to write code to patch everything together.
The implementation and behavior of routed events have many parallels to dependency properties. As with the dependency property discussion, we'll first look at how a simple routed event is implemented to make things more concrete. Then we'll examine some of the features of routed events and apply them to the About dialog.
A Routed Event Implementation
In most cases, routed events don't look very different from normal .NET events. As with dependency properties, no .NET languages (other than XAML) have an intrinsic understanding of the routed designation. The extra support is based on a handful of WPF APIs.
Listing 3.6 demonstrates how Button effectively implements its Click routed event. (Click is actually implemented by Button's base class, but that's not important for this discussion.)
Just as dependency properties are represented as public static DependencyProperty fields with a conventional Property suffix, routed events are represented as public static RoutedEvent fields with a conventional Event suffix. The routed event is registered much like a dependency property in the static constructor, and a normal .NET event—or event wrapper—is defined to enable more familiar use from procedural code and adding a handler in XAML with event attribute syntax. As with a property wrapper, an event wrapper must not do anything in its accessors other than call AddHandler and RemoveHandler.
Listing 3.6. A Standard Routed Event Implementation
public class Button : ButtonBase { // The routed event public static readonly RoutedEvent ClickEvent; static Button() { // Register the event Button.ClickEvent = EventManager.RegisterRoutedEvent("Click", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Button)); ... } // A .NET event wrapper (optional) public event RoutedEventHandler Click { add { AddHandler(Button.ClickEvent, value); } remove { RemoveHandler(Button.ClickEvent, value); } } protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { ... // Raise the event RaiseEvent(new RoutedEventArgs(Button.ClickEvent, this)); ... } ... }
These AddHandler and RemoveHandler methods are not inherited from DependencyObject, but rather System.Windows.UIElement, a higher-level base class of elements such as Button. (This class hierarchy is examined in more depth at the end of this chapter.) These methods attach and remove a delegate to the appropriate routed event. Inside OnMouseLeftButtonDown, RaiseEvent (also defined on the base UIElement class) is called with the appropriate RoutedEvent field to raise the Click event. The current Button instance (this) is passed as the source element of the event. It's not shown in this listing, but Button's Click event is also raised in response to a KeyDown event to support clicking with the spacebar or sometimes the Enter key.
Routing Strategies and Event Handlers
When registered, every routed event chooses one of three routing strategies—the way in which the event raising travels through the element tree. These strategies are exposed as values of a RoutingStrategy enumeration:
- Tunneling—The event is first raised on the root, then on each element down the tree until the source element is reached (or until a handler halts the tunneling by marking the event as handled).
- Bubbling—The event is first raised on the source element, then on each element up the tree until the root is reached (or until a handler halts the bubbling by marking the event as handled).
- Direct—The event is only raised on the source element. This is the same behavior as a plain .NET event, except that such events can still participate in mechanisms specific to routed events such as event triggers.
Handlers for routed events have a signature matching the pattern for general .NET event handlers: The first parameter is a System.Object typically named sender, and the second parameter (typically named e) is a class that derives from System.EventArgs. The sender parameter passed to a handler is always the element to which the handler was attached. The e parameter is (or derives from) an instance of RoutedEventArgs, a subclass of EventArgs that exposes four useful properties:
- Source—The element in the logical tree that originally raised the event.
- OriginalSource—The element in the visual tree that originally raised the event (for example, the TextBlock or ButtonChrome child of a standard Button).
- Handled—A Boolean that can be set to true to mark the event as handled. This is precisely what halts any tunneling or bubbling.
- RoutedEvent—The actual routed event object (such as Button.ClickEvent), which can be helpful for identifying the raised event when the same handler is used for multiple routed events.
The presence of both Source and OriginalSource enable you to work with the higher-level logical tree or the lower-level visual tree. This distinction only applies to physical events like mouse events, however. For more abstract events that don't necessarily have a direct relationship with an element in the visual tree (like Click due to its keyboard support), the same object is passed for both Source and OriginalSource.
Routed Events in Action
The UIElement class defines many routed events for keyboard, mouse, and stylus input. Most of these are bubbling events, but many of them are paired with a tunneling event. Tunneling events can be easily identified because, by convention, they are named with a Preview prefix. These events, also by convention, are raised immediately before their bubbling counterpart. For example, PreviewMouseMove is a tunneling event raised before the MouseMove bubbling event.
The idea behind having a pair of events for various activities is to give elements a chance to effectively cancel or otherwise modify an event that's about to occur. By convention, WPF's built-in elements only take action in response to a bubbling event (when a bubbling and tunneling pair is defined), ensuring that the tunneling event lives up to its "preview" name. For example, imagine you want to implement a TextBox that restricts its input to a certain pattern or regular expression (such as a phone number or zip code). If you handle TextBox's KeyDown event, the best you can do is remove text that has already been displayed inside the TextBox. But if you handle TextBox's PreviewKeyDown event instead, you can mark it as "handled" to not only stop the tunneling but also stop the bubbling KeyDown event from being raised. In this case, the TextBox will never receive the KeyDown notification and the current character will not get displayed.
To demonstrate the use of a simple bubbling event, Listing 3.7 updates the original About dialog from Listing 3.1 by attaching an event handler to Window's MouseRightButtonDown event. Listing 3.8 contains the C# code-behind file with the event handler implementation.
Listing 3.7. The About Dialog with an Event Handler on the Root Window
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="AboutDialog" MouseRightButtonDown="AboutDialog_MouseRightButtonDown" Title="About WPF Unleashed" SizeToContent="WidthAndHeight" Background="OrangeRed"> <StackPanel> <Label FontWeight="Bold" FontSize="20" Foreground="White"> WPF Unleashed (Version 3.0) </Label> <Label>© 2006 SAMS Publishing</Label> <Label>Installed Chapters:</Label> <ListBox> <ListBoxItem>Chapter 1</ListBoxItem> <ListBoxItem>Chapter 2</ListBoxItem> </ListBox> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"> <Button MinWidth="75" Margin="10">Help</Button> <Button MinWidth="75" Margin="10">OK</Button> </StackPanel> <StatusBar>You have successfully registered this product.</StatusBar> </StackPanel> </Window>
Listing 3.8. The Code-Behind File for Listing 3.7
using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Windows.Controls; public partial class AboutDialog : Window { public AboutDialog() { InitializeComponent(); } void AboutDialog_MouseRightButtonDown(object sender, MouseButtonEventArgs e) { // Display information about this event this.Title = "Source = " + e.Source.GetType().Name + ", OriginalSource = " + e.OriginalSource.GetType().Name + " @ " + e.Timestamp; // In this example, all possible sources derive from Control Control source = e.Source as Control; // Toggle the border on the source control if (source.BorderThickness != new Thickness(5)) { source.BorderThickness = new Thickness(5); source.BorderBrush = Brushes.Black; } else source.BorderThickness = new Thickness(0); } }
The AboutDialog_MouseRightButtonDown handler performs two actions whenever a right-click bubbles up to the Window: It prints information about the event to the Window's title bar, and it adds (then subsequently removes) a thick black border around the specific element in the logical tree that was right-clicked. Figure 3.7 shows the result. Notice that right-clicking on the Label reveals Source set to the Label but OriginalSource set to its TextBlock visual child.
Figure 3.7 The modified About dialog, after the first Label is right-clicked.
If you run this example and right-click on everything, you'll notice two interesting behaviors:
- Window never receives the MouseRightButtonDown event when you right-click on either ListBoxItem. That's because ListBoxItem internally handles this event as well as the MouseLeftButtonDown event (halting the bubbling) to implement item selection.
- Window receives the MouseRightButtonDown event when you right-click on a Button, but setting Button's Border property has no visual effect. This is due to Button's default visual tree, which was shown back in Figure 3.3. Unlike Window, Label, ListBox, ListBoxItem, and StatusBar, the visual tree for Button has no Border element.
Attached Events
The tunneling and bubbling of a routed event is natural when every element in the tree exposes that event. But WPF supports tunneling and bubbling of routed events through elements that don't even define that event! This is possible thanks to the notion of attached events.
Attached events operate much like attached properties (and their use with tunneling or bubbling is very similar to using attached properties with property value inheritance). Listing 3.9 changes the About dialog again by handing the bubbling SelectionChanged event raised by its ListBox and the bubbling Click event raised by both of its Buttons directly on the root Window. Because Window doesn't define its own SelectionChanged or Click events, the event attribute names must be prefixed with the class name defining these events. Listing 3.10 contains the corresponding code-behind file that implements the two event handlers. Both event handlers simply show a MessageBox with information about what just happened.
Listing 3.9. The About Dialog with Two Attached Event Handlers on the Root Window
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="AboutDialog" ListBox.SelectionChanged="ListBox_SelectionChanged" Button.Click="Button_Click" Title="About WPF Unleashed" SizeToContent="WidthAndHeight" Background="OrangeRed"> <StackPanel> <Label FontWeight="Bold" FontSize="20" Foreground="White"> WPF Unleashed (Version 3.0) </Label> <Label>© 2006 SAMS Publishing</Label> <Label>Installed Chapters:</Label> <ListBox> <ListBoxItem>Chapter 1</ListBoxItem> <ListBoxItem>Chapter 2</ListBoxItem> </ListBox> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"> <Button MinWidth="75" Margin="10">Help</Button> <Button MinWidth="75" Margin="10">OK</Button> </StackPanel> <StatusBar>You have successfully registered this product.</StatusBar> </StackPanel> </Window>
Listing 3.10. The Code-Behind File for Listing 3.9
using System.Windows; using System.Windows.Controls; public partial class AboutDialog : Window { public AboutDialog() { InitializeComponent(); } void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.AddedItems.Count > 0) MessageBox.Show("You just selected " + e.AddedItems[0]); } void Button_Click(object sender, RoutedEventArgs e) { if (e.AddedItems.Count > 0) MessageBox.Show("You just clicked " + e.Source); } }
Every routed event can be used as an attached event. The attached event syntax used in Listing 3.9 is valid because the XAML compiler sees the SelectionChanged .NET event defined on ListBox and the Click .NET event defined on Button. At run-time, however, AddHandler is directly called to attach these two events to the Window. Therefore, the two event attributes are equivalent to placing the following code inside the Window's constructor:
public AboutDialog() { InitializeComponent(); this.AddHandler(ListBox.SelectionChangedEvent, new SelectionChangedEventHandler(ListBox_SelectionChanged)); this.AddHandler(Button.ClickEvent, new RoutedEventHandler(Button_Click)); }