WPF 按钮按下/释放绑定

本文关键字:释放 绑定 按钮 WPF | 更新日期: 2023-09-27 18:32:12

我是WPF的新手,并试图尽我所能遵循MVVM按钮 我正在努力解决当前的问题我有一个视图模型类

public class MainViewModel
{
    private bool _Reset;
    public bool Reset{ get{ return _Reset;} set {_Reset = value;} }
    ...
}

现在我想绑定一个按钮,以便在我按下它时_Reset是真的,当我释放它时_Reset是假的我觉得命令模式对于简单的开/关来说工作量很大

有没有办法将按钮的 IsPressed 绑定到我的数据上下文中的属性

我想尽可能简单地做到这一点,因为我有十几个按钮都做其他属性的事情

WPF 按钮按下/释放绑定

所以你需要做的是导入System.Windows.Interactivity . 转到引用、添加引用、程序集、扩展。 你会在那里找到它。 接下来将其添加到您的项目中

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

现在,您可以使用"PreviewMouseLeftButtonDownPreviewMouseLeftButtonUp"事件。

<Button Content="Some Button">
        <inter:Interaction.Triggers>
            <inter:EventTrigger EventName="PreviewMouseLeftButtonDown">
                <inter:InvokeCommandAction Command="{Binding ButtonDown}"/>
            </inter:EventTrigger>
            <inter:EventTrigger EventName="PreviewMouseLeftButtonUp">
                <inter:InvokeCommandAction Command="{Binding ButtonUp}"/>
            </inter:EventTrigger>
        </inter:Interaction.Triggers>
    </Button>
 public class MainViewModel : ViewModelBase
{
    public MainViewModel()
    {
        ButtonDown = new RelayCommand(OnButtonDown);
        ButtonUp = new RelayCommand(OnButtonUp);
    }
    public RelayCommand ButtonDown { get; set; }
    public RelayCommand ButtonUp { get; set; }
    private void OnButtonUp()
    {
        Debug.WriteLine("Button Released");
    }
    private void OnButtonDown()
    {
        Debug.WriteLine("Button Pressed");
    }
}

如果使用 .NET Core 3.1/.NET 5.0 或更高版本,则System.Windows.Interactivity已被弃用,而是将Microsoft.Xaml.Behaviors.Wpf NuGet 包添加到项目中。该软件包的工作方式与此处的答案非常相似 the.NET 框架 4.8.x 或更低版本。

在 XAML 标头中,需要将引用添加到

<Control x:Class="YourNamespace.ControlName"
         ...
         xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
         ...>

现在,您可以装饰按钮或尝试事件触发器的其他项目,例如PreviewMouseLeftButtonDown

<Button Content="Click Me.">
    <b:Interaction.Triggers>
        <b:EventTrigger EventName="PreviewMouseLeftButtonDown">
             <b:InvokeCommandAction Command="{Binding OnButtonDown}"/>            
        </b:EventTrigger>
        <b:EventTrigger EventName="PreviewMouseLeftButtonUp">
             <b:InvokeCommandAction Command="{Binding OnButtonUp}"/>            
        </b:EventTrigger>
    </b:Interaction.Triggers>
</Button> 

现在,这允许绑定到视图模型类中的System.Windows.Input.ICommand属性。在此示例中,我使用 CommunityToolkitm.Mvvm 中的 RelayCommand 对象并写入调试控制台,但这可以通过对静态项的任何调用进行内联替换,或者如果操作不是静态项,则可以在视图模型类的构造函数中完成。

class ControlViewModel : ObservableObject
{
    //... 
    public ICommand OnButtonDown { get; } = new RelayCommand(()=> Debug.WriteLine("Button Down");
    public ICommand OnButtonUp { get; } = new RelayCommand(()=> Debug.WriteLine("Button Up");
    //...
}