0

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.

silviubogan
  • 3,343
  • 3
  • 31
  • 57

2 Answers2

2

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.

mm8
  • 163,881
  • 10
  • 57
  • 88
0

What you hit starts the ball rolling.

Or to be more precise.

The event bubbling.

Routed events can bubble up the visual tree and or tunnel down it.

The docs attempt to explain this:

https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/routed-events-overview

What this means is you click something which then becomes the originalsource of the event. This is resolved first because it's going to drive everything. It is not computed later.

It sort-of travels up and or down the visual tree and what source is set to will depend where you handle the event.

Andy
  • 11,864
  • 2
  • 17
  • 20