Routed Events in WPF

Hi guys. Today I’m going to show you what routed events are and why you should use them.

Routed Events definition and sample

Routed event – is specific type of event in WPF that is designed to travel through visual tree. This travel can be either in up or down direction. Let me show you on simple example event that travels up:

<StackPanel MouseLeftButtonDown="StackPanel_MouseLeftButtonDown"> <Rectangle Width="50" Height="50" Fill="Red"/> <Rectangle Width="50" Height="50" Fill="Red" Margin="5"/> </StackPanel>

And here is code from code-behind file:

public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void StackPanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { } }

In this case whenever you click on any Rectangle placed in StackPanel, MouseLeftButtonDown event will be invoked. If you examine event arguments you can see original source of event:


In our case, original source is Rectangle instance. This type of event is also known as bubbling event.

Conversely, there is type of event that can travel down through visual tree:

<StackPanel MouseLeftButtonDown="StackPanel_MouseLeftButtonDown" PreviewMouseLeftButtonDown="StackPanel_PreviewMouseLeftButtonDown"> <Rectangle Width="50" Height="50" Fill="Red"/> <Rectangle Width="50" Height="50" Fill="Red" Margin="5"/> </StackPanel>

As you can see, I’ve attached handler for PreviewMouseLeftButtonDown event. This type of event is also known as tunnel event. It’s a common convention to name tunnel events with “Preview” prefix.

You should know that tunnel events are fired first, so in our case method execution order looks like this:

  1. StackPanel_PreviewMouseLeftButtonDown
  2. StackPanel_MouseLeftButtonDown

Where Routed Events can be applied?

This type of event is powerful feature of WPF and can be used in those cases:

  1. You need to attach one event handler in one place for multiple elements in visual tree (like in the example above).
  2. You need to provide event data that will travel through visual tree and different handlers should be able to modify it.
  3. When you want to use EventSetter and EventTrigger with your event.
  4. When you want to use EventTrigger from Expression Blend SDK with your event.


To get more information about routed events consider this article. Bye Smile