*
Previous WPF-Commands WPF-Question-Answers-41-50 Next

WPF Routed Events

Routed Events in WPF

In WPF, routed events are a powerful extension of the standard .NET event model. They allow events to travel through the visual tree, giving multiple elements a chance to respond—even if they aren’t the direct source of the event.

🚦 What Is a Routed Event?

A routed event is an event that can be handled by multiple elements in the UI hierarchy. Unlike regular CLR events, routed events are backed by the WPF event system and are registered using the RoutedEvent class.

They support three routing strategies:

Strategy Description
Direct Behaves like a standard CLR event—only the source element handles it.
Bubbling Travels up the visual tree from the source to the root.
Tunneling Travels down the visual tree from the root to the source. Tunneling events are typically prefixed with Preview, like PreviewMouseDown.

🧩 How Routed Events Work

Imagine a Button inside a StackPanel inside a Window. When the button is clicked:

  • The Click event bubbles up from the Button to the StackPanel, then to the Window.
  • Any of these elements can handle the event—even if they didn’t raise it.

Example in XAML

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

Example in C#

private void StackPanel_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Handled at StackPanel level!");
}
  

🛠 Declaring a Custom Routed Event

You can define your own routed events like this:

public static readonly RoutedEvent MyCustomEvent = EventManager.RegisterRoutedEvent(
    "MyCustom", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyControl));

public event RoutedEventHandler MyCustom
{
    add { AddHandler(MyCustomEvent, value); }
    remove { RemoveHandler(MyCustomEvent, value); }
}
  

To raise it:

RaiseEvent(new RoutedEventArgs(MyCustomEvent));
  

🎯 Why Use Routed Events?

  • Decoupling: Logic can be centralized higher in the tree.
  • Flexibility: Multiple elements can respond to the same event.
  • Styling & Triggers: Routed events can be used in styles and templates.
  • Preview Handling: Tunneling allows interception before bubbling.
Back to Index
Previous WPF-Commands WPF-Question-Answers-41-50 Next
*
*