WPF routes event handling in UserControl

I have a UserControl WPF that contains a button. I also have a WPF window containing a button. In UserControl and Window, I put the following line in XAML:

UIElement.PreviewMouseLeftButtonDown="OnPreviewMouseLeftButtonDown" 

and in 'OnPreviewMouseLeftButtonDown' I put a debug print that displays args.Source.

When I click the button inside the window, I get the button as the EventArgs source. However, when I click on the button that is inside the UserControl (which is also inside the window, so I can test it, but not in the same window), I get the UserControl as the source of EventArgs.

I'm tired of seeing if there is any decorator around UserControl (using snoop), but that seems straightforward.

I can’t understand what is especially important in UserControl in WPF that I don’t get the right sender. Can someone explain to me what I am missing?

+4
source share
2 answers

While the question is old, I recently ran into a similar issue related to the ContextMenuOpening event. The usercontrol source code provided some scope of the search here , which contains the following section:

  // Set the EventArgs' source to be this UserControl internal override void AdjustBranchSource(RoutedEventArgs e) { e.Source=this; } 

So, obviously, UserControl sets the source of ANY routed event to itself. I have no idea why this happens, though ...

+1
source

Use e.OriginalSource as above. If you need to find a button, you can use VisualTreeHelper.GetParent to find the actual Button control.

0
source

All Articles