Inner GroupBox不会吞下Interactivity事件

时间:2017-01-13 12:03:47

标签: wpf xaml

我在父#!/usr/bin/env python import os print "Content-Type: text/html" print "Cache-Control: no-cache" print print "<html><body>" for headername, headervalue in os.environ.iteritems(): if headername.startswith("HTTP_"): print "<p>{0} = {1}</p>".format(headername, headervalue) print "</html></body>" 内有一个GroupBox。他们两个都有自己的

GroupBox

当我按下内部<i:Interaction.Triggers> <i:EventTrigger EventName="MouseLeftButtonDown"> <i:InvokeCommandAction Command="{Binding ...}" /> </i:EventTrigger> </i:Interaction.Triggers> 时,它会触发自己的GroupBox,然后也会触发父Command

我该如何预防?如何让内部Command吞下事件?

1 个答案:

答案 0 :(得分:1)

您可以使用另一个TriggerAction实现,它支持将事件args作为命令参数传递给命令,例如MvvmLight库中的EventToCommand类:

<GroupBox Header="Outer" xmlns:mvvm="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Platform">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseLeftButtonDown">
            <i:InvokeCommandAction Command="{Binding OuterCommand}"  />
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <TextBlock>...</TextBlock>
        <GroupBox Header="Inner" Grid.Row="1">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseLeftButtonDown">
                    <mvvm:EventToCommand Command="{Binding InnerCommand}" PassEventArgsToCommand="True"  />
                </i:EventTrigger>
            </i:Interaction.Triggers>
            <TextBlock>inner...</TextBlock>
        </GroupBox>
    </Grid>
</GroupBox>
public class ViewModel
{
    public ViewModel()
    {

        OuterCommand = new RelayCommand(arg => true, (arg)=> { MessageBox.Show("outer"); });
        InnerCommand = new RelayCommand(arg => true, 
            (arg) => 
            {
                MessageBox.Show("inner");
                MouseButtonEventArgs mbea = arg as MouseButtonEventArgs;
                if (mbea != null)
                    mbea.Handled = true;
            });
    }

    public RelayCommand OuterCommand { get; }

    public RelayCommand InnerCommand { get; }
}

此解决方案的丑陋之处在于视图模型依赖于与视图相关的MouseButtonEventArgs类型。如果你不喜欢这个,你可以按照@adabyron的建议实现你自己的行为:

MVVM Passing EventArgs As Command Parameter

然后,您可以直接在行为中设置MouseButtonEventArgs的Handled属性,而不是将其传递给视图模型。