場景
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}">