| WPF-Commands | WPF-Question-Answers-41-50 | |
WPF Routed Events |
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.
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. |
Imagine a Button inside a StackPanel inside a Window. When the button is clicked:
Click event bubbles up from the Button to the StackPanel, then to the Window.
<StackPanel ButtonBase.Click="StackPanel_Click">
<Button Content="Click Me" Click="Button_Click"/>
</StackPanel>
private void StackPanel_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Handled at StackPanel level!");
}
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));
| WPF-Commands | WPF-Question-Answers-41-50 | |