Reputation: 4157
The root problem I'm trying to solve is to gather all users input on my application. Clicks, keystrokes etc. And log element which got that input. In order to achieve this I've added PreviewKeyDown and PreviewMouseDown handlers to the main window and it works fine. But my application is based on a big framework and this framework may display some dialogs. I need a way to handle such dialogs and attach handler to them. Is there a way to create one centralized handler for this?
Upvotes: 1
Views: 482
Reputation: 13394
Since UI-Events are generally RoutedEvents, you can simply register a method of your own to handle every invocation of that event. If you for example want to see how your PreviewKeyDownEvent
tunnels through your UI:
EventManager.RegisterClassHandler(
typeof(UIElement),
UIElement.PreviewKeyDownEvent,
new RoutedEventHandler(localMethod));
With this you could "trace" a MouseDown
event tunnel down and bubble up your visual tree when you click a Button:
static UiEventHandler()
{
EventManager.RegisterClassHandler(
typeof(UIElement), UIElement.PreviewMouseDownEvent,
new RoutedEventHandler(PreviewMouseDown));
EventManager.RegisterClassHandler(
typeof(UIElement), UIElement.MouseDownEvent,
new RoutedEventHandler(MouseDown));
}
private static void MouseDown(object sender, RoutedEventArgs e)
{
Debug.WriteLine("MouseDown on " + sender.GetType());
}
private static void PreviewMouseDown(object sender, RoutedEventArgs e)
{
Debug.WriteLine("PreviewMouseDown on " + sender.GetType());
}
Output:
//Event hits Window and tunnels through the visual tree
PreviewMouseDown on WpfApplication10.MainWindow
PreviewMouseDown on System.Windows.Controls.Border
PreviewMouseDown on System.Windows.Documents.AdornerDecorator
PreviewMouseDown on System.Windows.Controls.ContentPresenter
PreviewMouseDown on System.Windows.Controls.Grid
PreviewMouseDown on System.Windows.Controls.Button
PreviewMouseDown on Microsoft.Windows.Themes.ButtonChrome
PreviewMouseDown on System.Windows.Controls.ContentPresenter
PreviewMouseDown on System.Windows.Controls.TextBlock
//Nobody handled the event, so it bubbles back up
MouseDown on System.Windows.Controls.TextBlock
MouseDown on System.Windows.Controls.ContentPresenter
MouseDown on Microsoft.Windows.Themes.ButtonChrome
//ButtonChrome handled the event as a 'Click'
Upvotes: 1