我在父GroupBox
中有一个GroupBox
。他们俩都有自己的
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonDown">
<i:InvokeCommandAction Command="{Binding ...}" />
</i:EventTrigger>
</i:Interaction.Triggers>
当我按下内GroupBox
时,它会触发自己的Command
,然后父Command
也会被触发。
我该如何防止这种情况?如何让内GroupBox
吞噬事件?
您可以使用另一个支持将事件参数作为命令参数传递给命令的 TriggerAction 实现,例如 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 将事件参数作为命令参数传递
然后,您可以直接在行为中设置 MouseButtonEventArgs 的 Handle 属性,而不是将其传递给视图模型。