MVVM风格的按钮按下和释放命令

本文关键字:释放 命令 风格 按钮 MVVM | 更新日期: 2023-09-27 18:28:03

我很高兴使用ICommand实现来处理按钮上的单个操作:

<Button Command="{Binding Path=ActionDown}">Press Me</Button>

通过RelayCommand 实现ICommand

但我找不到一种简单的方法来为媒体发布行动提供行动(既在SO上,也在网络间的其他地方)。IE我想做一些类似的事情,但我不知道如何做:

<Button PressCommand="{Binding Path=ActionDown}" ReleaseCommand="{Binding Path=ActionUp}">Press and Release Me</Button>

处理此类需求的正确MVVM方式是什么?

MVVM风格的按钮按下和释放命令

您可以使用System.Windows.Interactivity中的EventTrigger来触发事件上的命令

<Button Content="Press Me">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="PreviewMouseLeftButtonDown">
            <i:InvokeCommandAction Command="{Binding Path=ActionDown}"/>
        </i:EventTrigger>
        <i:EventTrigger EventName="PreviewMouseLeftButtonUp">
            <i:InvokeCommandAction Command="{Binding Path=ActionUp}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

您需要添加对System.Windows.Interactivity的引用并定义名称空间

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

您可以轻松地从Button扩展创建自己的类,为MouseDown和MouseUp定义可绑定的命令。

示例:

public class PressAndReleaseButton : Button
{
    public static readonly DependencyProperty PressCommandProperty = DependencyProperty.Register(
        "PressCommand", typeof(ICommand), typeof(PressAndReleaseButton), new PropertyMetadata(null));
    /// <summary>
    /// The Press command to bind
    /// </summary>
    public ICommand PressCommand
    {
        get { return (ICommand)GetValue(PressCommandProperty); }
        set { SetValue(PressCommandProperty, value); }
    }
    public static readonly DependencyProperty ReleaseCommandProperty = DependencyProperty.Register(
        "ReleaseCommand", typeof(ICommand), typeof(PressAndReleaseButton), new PropertyMetadata(null));
    /// <summary>
    /// The Release command to bind
    /// </summary>
    public ICommand ReleaseCommand
    {
        get { return (ICommand)GetValue(ReleaseCommandProperty); }
        set { SetValue(ReleaseCommandProperty, value); }
    }
    /// <summary>
    /// Default constructor registers mouse down and up events to fire commands
    /// </summary>
    public PressAndReleaseButton()
    {
        MouseDown += (o, a) => 
                 {
                     if (PressCommand.CanExecute(null)) PressCommand.Execute(null);
                 }
        MouseUp += (o, a) => 
                 {
                     if (ReleaseCommand.CanExecute(null)) ReleaseCommand.Execute(null);
                 } 
    }
}