场景
Button与RadioButton配合使用。RadioButton选中时,按下Button的左键,执行命令,抬起左键后命令终止;RadioButton未选中时,点击Button,执行另一个命令。
Button需要实现MouseClick
、MouseLeftButtonDown
和MouseLeftButtonUp
三个事件。默认的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}">