使用MVVM交互防止子冒泡事件冒泡到父ListView项

时间:2014-01-09 03:09:21

标签: wpf xaml mvvm windows-phone-8

点击以下XAML中的StackPanel会同时触发MyCommand1MyCommand2

<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>           

如何在保持正确的MVVM风格的同时确保只触发MyCommand2

1 个答案:

答案 0 :(得分:2)

解决方案是编写自己的EventTrigger并继承自System.Windows.Interactivity.EventTrigger&#39;。这会产生以下类,然后您可以在XAML中使用它来进行命令绑定。

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);
    }
}

如果您正在开发Windows Phone,而不是GestureEventArgs,而后者没有RoutedEventArgs属性。