【WPF】如何绑定多个Command到一个Button上,使用EventTrigger

场景

Button与RadioButton配合使用。RadioButton选中时,按下Button的左键,执行命令,抬起左键后命令终止;RadioButton未选中时,点击Button,执行另一个命令。

Button需要实现MouseClickMouseLeftButtonDownMouseLeftButtonUp三个事件。默认的command只能实现MouseClick的效果。由于采用的MVVM架构,还是希望所有的事件都通过Command实现。

解决方法

通过EventTrigger实现。需要用到Blend SDK中的System.Windows.Interactivity.dll,如果解决方案的“添加引用”中找不到这个dll文件,可以在NuGet中安装System.Windows.Interactivity.WPF包。

xaml:

在头部添加如下命名空间,即引用上述的dll文件。

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

button标签下使用Interaction.Trigger,如下所示:

<Button Grid.Row="0" Grid.Column="1" Content="Y+"
        Command="{Binding YStepMoveCommand}" CommandParameter="{StaticResource False}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseLeftButtonDown">
            <i:InvokeCommandAction Command="{Binding YContinueMoveCommand}" CommandParameter="{StaticResource False}"/>
        </i:EventTrigger>
        <i:EventTrigger EventName="MouseLeftButtonUp">
            <i:InvokeCommandAction Command="{Binding StopMoveCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

PS:这里应该用PreviewMouseLeftButtonDown,否则命令不起作用。

ViewModel:

viewmodel中的实现方式和一般command一样。

public ViewModel()
{
    public ICommand YContinueMoveCommand => new DelegateCommand(YContinueMove);
    public ICommand YStepMoveCommand => new DelegateCommand(YStepMove);
    public ICommand StopMoveCommand => new DelegateCommand(StopMove);
    
    private void YContinueMove(object commandParameter)
    {   }
    ......
}

参考:How to bind different DelegateCommands to button down and button up

通过 CommandParameter 传递值

CommandParameter只能传递字符串或者绑定的值

最简单的方法是:将需要传递的非字符串在Resource中定义。在App.xaml中。

首先,在Application标签中声明命名空间。

xmlns:System="clr-namespace:System;assembly=mscorlib"

然后,在Application.Resources中定义值,比如bool值。

<System:Boolean x:Key="FalseValue">False</System:Boolean>
<System:Boolean x:Key="TrueValue">True</System:Boolean>

最后,在需要绑定的命令中使用。

<Button Grid.Row="0" Grid.Column="1" Content="Y+"
        Command="{Binding YStepMoveCommand}" CommandParameter="{StaticResource False}">

参考:Boolean CommandParameter in XAML

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值