Search code examples
c#wpfmouseeventhittestrouted-events

How is RoutedEventArgs.OriginalSource computed?


I have read here and in the MS docs that it is determined by hit testing, but the example at the end of this question is against this, or so I understand currently.

Here I have read that it is the first object that raised the event, and I do not know what does this mean, i.e. in the example below.

My current understanding

Given this code:

private void Handler(object sender, RoutedEventArgs e)
{
    // what does it mean here: sender, e.Source and e.OriginalSource ?
}
  • sender - the element that handles the event (to which the handler is attached)
  • e.Source - the element for which the event started progressing through the visual tree (either from top to bottom, or from bottom to top)
  • e.OriginalSource - the deepest element determined through hit testing which is inside the one for which the event started progressing through the visual tree

The example

Given the visual tree of the following source XAML:

<StackPanel x:Name="sp" Button.Click="Handler">
    <Button x:Name="btn1">button 1</Button>
    <Button x:Name="btn2">button 2</Button>
    <Button x:Name="btn3" Padding="5">
        <Rectangle Width="100" Height="100" Fill="Blue" x:Name="r"/>
    </Button>
</StackPanel>

and the same handler as above:

private void Handler(object sender, RoutedEventArgs e)
{
    // what does it mean here: sender, e.Source and e.OriginalSource ?
}

When a click is made on:

  • btn1: sender will be sp, e.Source will be btn1, e.OriginalSource will be btn1
  • btn2: sender will be sp, e.Source will be btn2, e.OriginalSource will be btn2
  • btn3: sender will be sp, e.Source will be btn3, e.OriginalSource will be:
    • r if the click is made over the blue Rectangle (here I was wrong and I do not know why)
    • btn3 if the click is made over the space in btn3 around r

Instead of r in the latest element in the list above, I get e.OriginalSource == btn3.

The official docs are here.

Thank you.


Solution

  • The Rectangle doesn't raise any Button.Click event that you handle. It does however raise a MouseLeftButtonDown (that the Button handles internally) which you can confirm if you handle the PreviewMouseLeftButtonDown of the StackPanel and check the OriginalSource property in the event handler.