2

Binding a RoutedEvent for the "Click" event of static buttons contained in a StackPanel is easy. The RoutedEventArgs will contain the button as the e.Source of the event.

XAML:

<StackPanel Grid.Column="1" Button.Click="RoutedEventHandler">
    <Button Name="btn1" Content="btn1" />
    <Button Name="btn2" Content="btn2" />
</StackPanel>

Code Behind:

private void RoutedEventHandler(object sender, RoutedEventArgs e)
{
    MessageBox.Show(((FrameworkElement)e.Source).Name);
}

However - handling routed events with "ListViewItem.MouseDoubleClick" will result the ListView container object in the e.Source, instead of the expected ListViewItem object.

XAML:

<ListView Name="lbAnecdotes" 
    ListViewItem.MouseDoubleClick="RoutedEventHandler">
    <ListView.ItemTemplate >
        <DataTemplate>
            <WrapPanel >
                <TextBlock Text="{Binding Path=Name}" />
            </WrapPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView >

Can you explain the inconsistency?

orberkov
  • 1,145
  • 2
  • 13
  • 27
  • 1
    Don't you find it logical that when you set the handler on the `ListView`, you get the same `ListView` as your `e.Source`? You can always refer to `e.OriginalSource` if you want the original source. – Vanlalhriata Jul 22 '13 at 09:18
  • No, please note that this is a **bubbling** event: **ListViewItem**.MouseDoubleClick=... – orberkov Jul 22 '13 at 09:37
  • 1
    Ah. I didn't catch the whole point of your question until I reread it just now. My apologies. And interesting question. +1'd – Vanlalhriata Jul 22 '13 at 09:52
  • What do you expect will see in the `e.Source`? `TextBlock`, `WrapPanel`? – Anatoliy Nikolaev Jul 22 '13 at 10:20
  • Equivalently to expecting to see the Button object on the first case (Button.Click), I expect to see the ListViewItem object (ListViewItem.MouseDoubleClick) – orberkov Jul 22 '13 at 10:22

1 Answers1

1

Simply put, the ListViewItem.MouseDoubleClick event is not a RoutedEvent like the ButtonBase.Click event. It uses the MouseButtonEventHandler delegate and a Direct routing strategy where as the ButtonBase.Click event is a RoutedEvent with a Bubbling strategy. They are different types of events and are implemented differently.

Sheridan
  • 68,826
  • 24
  • 143
  • 183