Liel
Liel

Reputation: 2437

Preventing child Tap event from bubbling to parent ListView item using MVVM Interactions

Tapping the StackPanel in the following XAML will trigger both MyCommand1 and MyCommand2:

<phone:LongListSelector ItemsSource="{Binding SomeSource}">
    <phone:LongListSelector.ItemTemplate>
        <DataTemplate >
            <Grid>
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="Tap">
                        <i:InvokeCommandAction Command="{Binding MyCommand1}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>

                <StackPanel >
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="Tap">
                            <i:InvokeCommandAction Command="{Binding MyCommand2}" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </StackPanel>
            </Grid>
        </DataTemplate>
    </phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>           

How is it possible to make sure that only MyCommand2 is triggered, while maintaining proper MVVM style?

Upvotes: 0

Views: 1167

Answers (1)

Marius Bughiu
Marius Bughiu

Reputation: 1017

The solution is to write your own EventTrigger and inherit from 'System.Windows.Interactivity.EventTrigger'. That results in the following class which you can then use in XAML for the command binding.

public class EventTriggerWithoutPropagation : System.Windows.Interactivity.EventTrigger
{
    protected override void OnEvent(System.EventArgs eventArgs)
    {
        var routedEventArgs = eventArgs as RoutedEventArgs;
        if (routedEventArgs != null)
            routedEventArgs.Handled = true;

        base.OnEvent(eventArgs);
    }
}

If you're developing for Windows Phone cast to GestureEventArgs instead of RoutedEventArgs as the latter doesn't have the Handled property.

Upvotes: 2

Related Questions