Question

I'm working through the 70-511 book, and am looking at the section on Routed Events. I noticed it mentions that bubbling-tunneling event pairs share the same EventArgs instance, so if you handle the tunneling event (eg PreviewMouseDown), it halts the paired bubbling event (eg MouseDown); I've tried this and it works... But, if I test for equality each time the event handler fires (for test purposes I'm using 1 event handler for both events) it seems as though the EventArgs are NOT the same instance (ie they have different hashvalues and Object.Equals returns false)... It would greatly improve my understanding of how routed events work if I could figure out why this is!

Any .NET gurus our there care to explain?

I've checked out the Pro WPF book (excellent book) and this also just states: "To make life more interesting, if you mark the tunneling event as handled, the bubbling event won’t occur. That’s because the two events share the same instance of the RoutedEventArgs class."

If the two events share the SAME INSTANCE of a class, shouldn't the eventargs have the same hashvalues and return 'True' for Object.Equals???

private RoutedEventArgs args;

private void MouseDownHandler(object sender, MouseButtonEventArgs e)
{
    listEvents.Items.Add(string.Format("{0} - {1} - {2} - {3}",
        sender.GetType().Name, e.RoutedEvent.ToString(), e.Source.GetType().Name,
        e.OriginalSource.GetType().Name));
    listEvents.Items.Add(e.GetHashCode().ToString());
    if (args != null) listEvents.Items.Add(e.Equals(args).ToString());
    args = e;
}

The XAML:

<Window x:Class="Chapter_2___WPF_RoutedEvents.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="428" Width="658"
    PreviewMouseDown="MouseDownHandler" MouseDown="MouseDownHandler">
    <Grid Name="grid"
          MouseDown="MouseDownHandler" PreviewMouseDown="MouseDownHandler">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <ListBox Name="listEvents" Grid.Column="1"/>
        <Button Content="Click Me!" Width="150" Height="50" Margin="10" Grid.Column="0"
                MouseDown="MouseDownHandler" PreviewMouseDown="MouseDownHandler"/>
    </Grid>
</Window>

No correct solution

OTHER TIPS

When I run your code and click the button, it does return the same hash code and 'True' for e.Equals(args). If I click again, e.Equals(args) returns 'False' because it is a new instance of RoutedEventArgs for each click, but the next one returns True because the tunneling event is the same as the bubbling event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top