【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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章