In WPF there are bubbling Routed Events that travel up the visual tree until they are marked as handled by an event handler. This is for example the click event of a button control.
<Button Content="Click me" Click="Button_Click"/>
The code behind of this can be for example:
private void Button_Click(object sender, RoutedEventArgs e) { // Do something e.Handled = true; }
The mouse click event is set to handled in the button click event handler. That means usually, parent objects in the visual tree can’t react on the mouse click event anymore. If we would have another event handler attached to the click event of the window, it will not be called.
private void Window_Click(object sender, RoutedEventArgs e) { // Do something on the window level }
However there is a way to still accomplish that. Instead of attaching the event handler for the window click event in XAML, we will use a different approach:
public MainWindow() .{ InitializeComponent(); AddHandler(Button.ClickEvent, new RoutedEventHandler(Window_Click), true); }
Here we add the event handler in the constructor of the window using the AddHandler method.This takes two parameters: The event, and a RoutedEventHandler object. The RoutedEventHandler constructor takes the event handling method that we used before.
It is overloaded that it can have a second parameter telling if also events should be considered that have been handled before.