WPF - Routed Events

Introduction

A routed event is a type of event that can invoke handlers on multiple listeners in an element tree rather than just the object that raised the event. It is basically a CLR event that is supported by an instance of the Routed Event class. It is registered with the WPF event system. RoutedEvents have three main routing strategies which are as follows,

  • Direct Event
  • Bubbling Event
  • Tunnel Event

Direct Event

A direct event is similar to events in Windows forums which are raised by the element in which the event is originated.

Unlike a standard CLR event, direct routed events support class handling and they can be used in Event Setters and Event Triggers within your style of your Custom Control.

A good example of a direct event would be the MouseEnter event.

Bubbling Event

A bubbling event begins with the element where the event is originated. Then it travels up the visual tree to the topmost element in the visual tree. So, in WPF, the topmost element is most likely a window.

Tunnel Event

Event handlers on the element tree root are invoked and then the event travels down the visual tree to all the children nodes until it reaches the element in which the event originated.

The difference between a bubbling and a tunneling event is that a tunneling event will always start with a preview.

In a WPF application, events are often implemented as a tunneling/bubbling pair. So, you'll have a preview MouseDown and then a MouseDown event.

Given below is a simple example of a Routed event in which a button and three text blocks are created with some properties and events. 

  1. <Window x:Class="WPFRoutedEvents.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="450" Width="604" ButtonBase.Click="Window_Click">  
  2.     <Grid>  
  3.         <StackPanel Margin="20" ButtonBase.Click="StackPanel_Click">  
  4.             <StackPanel Margin="10">  
  5.                 <TextBlock Name="txt1" FontSize="18" Margin="5" Text="This is a  
  6.   
  7. TextBlock 1" />  
  8.                 <TextBlock Name="txt2" FontSize="18" Margin="5" Text="This is a  
  9.   
  10. TextBlock 2" />  
  11.                 <TextBlock Name="txt3" FontSize="18" Margin="5" Text="This is a  
  12.   
  13. TextBlock 3" /> </StackPanel>  
  14.             <Button Margin="10" Content="Click me" Click="Button_Click" Width="80" /> </StackPanel>  
  15.     </Grid>  
  16. </Window>   

Here is the C# code for the Click events implementation for Button, StackPanel, and Window. 

  1. using System.Windows;  
  2. namespace WPFRoutedEvents {  
  3.     /// <summary>  
  4.     /// Interaction logic for MainWindow.xaml  
  5.     /// </summary>  
  6.     public partial class MainWindow: Window {  
  7.         public MainWindow() {  
  8.             InitializeComponent();  
  9.         }  
  10.         private void Button_Click(object sender, RoutedEventArgs e) {  
  11.             txt1.Text = "Button is Clicked";  
  12.         }  
  13.         private void StackPanel_Click(object sender, RoutedEventArgs e) {  
  14.             txt2.Text = "Click event is bubbled to Stack Panel";  
  15.         }  
  16.         private void Window_Click(object sender, RoutedEventArgs e) {  
  17.             txt3.Text = "Click event is bubbled to Window";  
  18.         }  
  19.     }  
  20. }   

When you compile and execute the above code, it will produce the following window:

 

When you click on the button, the text blocks will get updated, as shown below.

 

If you want to stop the routed event at any particular level, then you will need to set the

  1. e.Handled = true;  

 

Let’s change the StackPanel_Click event as shown below, 

  1. private void StackPanel_Click(object sender, RoutedEventArgs e)   
  2. {  
  3.     txt2.Text = "Click event is bubbled to Stack Panel";  
  4.     e.Handled = true;  
  5. }   

When you click on the button, you will observe that the click event will not be routed to the window and will stop at the stackpanel and the 3rd text block will not be updated.

 

Custom Routed Events

In .NET framework, custom routed event can also be defined. You need to follow the steps given below to define a custom routed event in C#.

  • Declare and register your routed event with system call RegisterRoutedEvent.
  • Specify the Routing Strategy, i.e. Bubble, Tunnel, or Direct.
  • Provide the event handler.

Let’s take an example to understand more about custom routed events. Follow the steps given below,

  1. Create a new WPF project with WPFCustomRoutedEvent
  2. Right click on your solution and select Add > New Item...
  3. The following dialog will open, now select Custom Control (WPF) and name it

    MyCustomControl.



  4. Click the Add button and you will see that two new files (Themes/Generic.xaml and MyCustomControl.cs) will be added in your solution.

    The following XAML code sets the style for the custom control in Generic.xaml file.

    1. <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WPFCustomRoutedEvent">  
    2.     <Style TargetType="{x:Type local:MyCustomControl}">  
    3.         <Setter Property="Margin" Value="50"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type local:MyCustomControl}"><Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"><Button x:Name="PART_Button" Content="Click Me" /></Border></ControlTemplate></Setter.Value></Setter>  
    4.     </Style>  
    5. </ResourceDictionary>  

    Given below is the C# code for the MyCustomControl class which inherits from the Control class in which a custom routed event Click is created for the custom control. 
  1. using System.Windows;  
  2. using System.Windows.Controls;  
  3. namespace WPFCustomRoutedEvent {  
  4.     public class MyCustomControl: Control {  
  5.         static MyCustomControl() {  
  6.             DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));  
  7.         }  
  8.         public override void OnApplyTemplate() {  
  9.             base.OnApplyTemplate();  
  10.             //demo purpose only, check for previous instances and remove the handler first  
  11.             var button = GetTemplateChild("PART_Button") as Button;  
  12.             if (button != null) button.Click += Button_Click;  
  13.         }  
  14.         void Button_Click(object sender, RoutedEventArgs e) {  
  15.             RaiseClickEvent();  
  16.         }  
  17.         public static readonly RoutedEvent ClickEvent = EventManager.RegisterRoutedEvent("Click", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyCustomControl));  
  18.         public event RoutedEventHandler Click {  
  19.             add {  
  20.                 AddHandler(ClickEvent, value);  
  21.             }  
  22.             remove {  
  23.                 RemoveHandler(ClickEvent, value);  
  24.             }  
  25.         }  
  26.         protected virtual void RaiseClickEvent() {  
  27.             RoutedEventArgs args = new  
  28.             RoutedEventArgs(MyCustomControl.ClickEvent);  
  29.             RaiseEvent(args);  
  30.         }  
  31.     }  
  32. }   

Here is the custom routed event implementation in C# which will display a message box when the user clicks it. 

  1. using System.Windows;  
  2. namespace WPFCustomRoutedEvent   
  3. {  
  4.     // <summary>  
  5.     // Interaction logic for MainWindow.xaml  
  6.     // </summary>  
  7.     public partial class MainWindow: Window {  
  8.         public MainWindow() {  
  9.             InitializeComponent();  
  10.         }  
  11.         private void MyCustomControl_Click(object sender, RoutedEventArgs e) {  
  12.             MessageBox.Show("It is the custom routed event of your custom control");  
  13.         }  
  14.     }  
  15. }   

Here is the implementation in MainWindow.xaml to add the custom control with a routed event Click.

  1. <Window x:Class="WPFCustomRoutedEvent.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WPFCustomRoutedEvent" Title="MainWindow" Height="350" Width="604">  
  2.     <Grid>  
  3.         <local:MyCustomControl Click="MyCustomControl_Click" /> </Grid>  
  4. </Window>   

When the above code is compiled and executed, it will produce the following window which contains a custom control.

 

When you click on the custom control, it will produce the following message.