2
votes

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?

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
No, please note that this is a bubbling event: ListViewItem.MouseDoubleClick=...orberkov
Ah. I didn't catch the whole point of your question until I reread it just now. My apologies. And interesting question. +1'dVanlalhriata
What do you expect will see in the e.Source? TextBlock, WrapPanel?Anatoliy Nikolaev
Equivalently to expecting to see the Button object on the first case (Button.Click), I expect to see the ListViewItem object (ListViewItem.MouseDoubleClick)orberkov

1 Answers

1
votes

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.