#594 – Routed Events Under the Covers

Traditional CLR events are basically a wrapper around a private instance of a multicast delegate type.  When you add an event handler using the += operator, your handler gets added to the delegate’s invocation list.

// CLR event under the covers
private EventHandler barked;
public event EventHandler Barked
{
    add { barked += value; }
    remove { barked -= value; }
}

Routed events in WPF look like standard CLR events because they are exposed via a CLR event.  But they are implemented differently.

When you use += for a routed event, the UIElement.AddHandler method is called.

    // From ButtonBase.cs
    public static readonly RoutedEvent ClickEvent;
    public event RoutedEventHandler Click { add { AddHandler(ClickEvent, value); } remove { RemoveHandler(ClickEvent, value); } }

The AddHandler method adds information about both the event and the handler to list of event handlers that is stored within the UIElement, used when the event is raised.

Advertisement

#593 – AddHandler Method Can Add Handler for Any Event

If you’re adding an event handler from code, rather than specifying the handler in XAML, you can just use the += notation for an event that is defined for the control in question.  For example, the Button control defines a Click control, so you can do the following:

myButton.Click += new RoutedEventHandler(Button_Click);

But let’s say that you want to add a handler for the Click event to a StackPanel control, which does not define the Click event, and you want to do it from code.  You can then use the AddHandler syntax:

myStackPanel.AddHandler(ButtonBase.ClickEvent, (RoutedEventHandler)HandleTheClick);

Notice that the AddHandler method accepts any routed event type as its first parameter.  This means that any UIElement instance can call its AddHandler method to indicate that it wants to handle any routed event.  Even though StackPanel doesn’t define a Click event, it can handle the Button’s Click event.

#592 – Adding an Event Handler in Code

You typically specify handlers for routed events in XAML:

        <Button Content="Like" Click="Button_Click"/>

You then add the code for the handler in your code-behind:

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Click");
        }

You can also add the handler from code. Adding a handler to the Button control for the  Click event requires that you give the Button control a name that you can then reference from your code-behind.

        <Button Name="myButton" Content="Like"/>

You can then add a handler by using the += operator on the event for which you want a handler.

myButton.Click += new RoutedEventHandler(Button_Click);

This is equivalent to calling the UIElement.AddHandler method.

            myButton.AddHandler(ButtonBase.ClickEvent, (RoutedEventHandler)Button_Click);

#591 – You Can Attach Any Routed Event to Any Control

When you attach an event handler to a control, you most typically attach a handler for an event that is defined for that control.  For example, the Button control has a Click event defined.

<Button Content="Like" Click="Button_Click"/>

In WPF, however, you can actually attach any routed event to any control–whether or not that control defines the event or not.  For example, we can attach a handler for the Click event to a StackPanel object, using the full name for the ButtonBase.Click event.

A control won’t normally fire events that it doesn’t define, except that when events are routed, they can fire on every control higher up (or down) in the logical tree.

    <StackPanel ButtonBase.Click="StackPanel_Click">
        <Button Content="Like" Click="Button_Click"/>
    </StackPanel>

Now, when you click on the Button, both handlers that you define will see the Click event, because it bubbles up the logical tree.

#590 – Not All Routed Events Exist in Pairs

Many of the routed events defined for common user interface elements in WPF exist in pairs–with an Xyz event that is bubbling and a corresponding PreviewXyz event that is tunneling.  But there are also many routed events that exist without a corresponding paired event.

For example, the Click event, defined in ButtonBase is a routed event that is a bubbling event.  When a user clicks on a Button, the Click event fires on the Button and then propagates up the logical and visual trees.

#589 – Standard Tunneling/Bubbling Event Pairs

Here are the the most important paired tunneling/bubbling events for UIElement objects:

  • PreviewDragEnter / DragEnter – Dragging something onto element
  • PreviewDragLeave / DragLeave – Dragging something off of element
  • PreviewDragOver / DragOver – Dragging something over element
  • PreviewDrop / Drop – Drop something on element after dragging
  • PreviewGiveFeedback/ GiveFeedback – Dragging starts, element sends info to source
  • PreviewGotKeyboardFocus / GotKeyboardFocus – Element gains keyboard focus
  • PreviewKeyDown / KeyDown – Key pressed while element has focus
  • PreviewKeyUp / KeyUp – Key released
  • PreviewLostKeyboardFocus / LostKeyboardFocus – Element loses keyboard focus
  • PreviewMouseDown / MouseDown – Mouse button pressed while over element
  • PreviewMouseLeftButtonDown / MouseLeftButtonDown – left mouse button pressed
  • PreviewMouseLeftButtonUp / MouseLeftButtonUp – left mouse button released
  • PreviewMouseMove / MouseMove – mouse moves over element
  • PreviewMouseRightButtonDown / MouseRightButtonDown – right mouse button pressed
  • PreviewMouseRightButtonUp / MouseRightButtonUp – right mouse button released
  • PreviewMouseUp / MouseUp – mouse button released
  • PreviewMouseWheel / MouseWheel – mouse wheel rotated
  • PreviewQueryContinueDrag / QueryContinueDrag – keyboard/mouse changes while dragging
  • PreviewTextInput / TextInput – element gets text
  • PreviewTouchDown / TouchDown – finger touches element
  • PreviewTouchMove / TouchMove – finger moves over element
  • PreviewTouchUp / TouchUp – finger raised while over element

#588 – If You Handle PreviewKeyDown Event, KeyDown Won’t Fire

The PreviewKeyDown and KeyDown events in WPF are paired routed events.  When a user presses a key in a control, the PreviewKeyDown event fires first, as a tunneling event.  When the event has propagated down the logical tree to the control where the key press originated, the KeyDown event fires.  KeyDown propagates up the logical tree, since it is defined as a bubbling event.

If you handle the PreviewKeyDown event as it is propagating down the tree and you mark the event as handled (setting KeyEventArgs.Handled to true), the PreviewKeyDown event will not continue propagating down the tree.

But if you mark PreviewKeyDown as handled, the corresponding KeyDown event will not fire at all.  This works because the two events share the same instance of a KeyEventArgs object, so when PreviewKeyDown marks the event as handled, KeyDown also treats the event as handled.

#587 – The Purpose of Tunneling and Bubbling Events

Many predefined routed events in WPF are available as pairs of events–one tunneling and one bubbling.  The tunneling event typically fires first.  E.g. PreviewKeyDown and KeyDown.

Tunneling events are useful if you want to do some filtering out of different events, for example filtering out disallowed keystrokes.  This might be useful to do in a higher-level parent control, so lower level controls like buttons don’t have to all deal with the invalid input.

 

#586 – Bubbling and Tunneling Events Are Typically Paired

Events defined for preexisting controls in WPF (e.g. a Button) are typically routed events–meaning that the event is propagated up or down the logical tree.  Routed events can either be bubbling events (they propagate up the tree) or tunneling events (they propagate down the tree).

Many events in WPF related to user input are available in pairs, with both a bubbling and a corresponding tunneling event.  For example, the KeyDown event (bubbling) has a corresponding PreviewKeyDown event (tunneling).

When events are paired, the tunneling events will typically fire first, followed by the paired bubbling event.

  1. User presses key
  2. Main Window sees PreviewKeyDown
  3. Outer StackPanel sees PreviewKeyDown
  4. Inner StackPanel sees PreviewKeyDown
  5. TextBox sees PreviewKeyDown
  6. TextBox sees KeyDown
  7. Inner StackPanel sees KeyDown
  8. Outer StackPanel sees KeyDown
  9. Main Window sees KeyDown

#585 – Tunneling Events Propagate Down the Logical Tree

In WPF, bubbling events originate in the control where the event occurred and then propagate up the logical or visual tree.  By contrast, tunneling events will be seen first by controls at the top of the hierarchy and then propagate down until they reach the control where the event originated.

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero"
    xmlns:loc="clr-namespace:WpfApplication11"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    x:Class="WpfApplication11.MainWindow"
    x:Name="Window" Title="Routed Events" Width="400"
    PreviewKeyDown="winMain_PreviewKeyDown">

    <StackPanel Name="spMain" Orientation="Vertical" PreviewKeyDown="spMain_PreviewKeyDown">
        <Label Content="Some good movies:"/>
        <StackPanel Orientation="Horizontal" Margin="10" PreviewKeyDown="spLawrence_PreviewKeyDown">
            <Label Content="Lawrence of Arabia" FontWeight="Bold"/>
            <Label Content="David Lean"/>
            <Button Content="Like" Padding="8,0"/>
            <TextBox Width="75" Margin="5,2" PreviewKeyDown="tbLawrence_PreviewKeyDown"/>
        </StackPanel>
    </StackPanel>
</Window>