简体   繁体   English

WPF按钮按下/释放绑定

[英]WPF Button Pressed/Released Binding

I am new to WPF and trying to do my best to follow the MVVM button Im struggling with a current problem I have a view Model class 我是WPF的新手并且尽力遵循MVVM按钮我正在努力解决当前的问题我有一个视图模型类

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

Now I want to bind a button so that if while Im pressing it _Reset is true and when I release it _Reset is false I feel like the command pattern is alot of work for a simple on/off 现在我想绑定一个按钮,这样如果我按下它_Reset是真的当我释放它时_Reset是假的我觉得命令模式很多工作对于一个简单的开/关

Is there a way to bind the IsPressed of a button to a property from my data context 有没有办法将按钮的IsPressed绑定到我的数据上下文中的属性

I want to do this as simple as possible because I have a dozen or so buttons all doing the type of thing just other properties 我想尽可能简单地做到这一点因为我有十几个按钮都在做其他属性的事情

So what you are going to need to do is import System.Windows.Interactivity . 所以你需要做的是导入System.Windows.Interactivity Go to references, add reference, Assemblies, Extensions. 转到参考,添加参考,装配,扩展。 You will find it there. 你会在那里找到它。 Next add it to your project 接下来将其添加到您的项目中

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

you can now use the PreviewMouseLeftButtonDown and PreviewMouseLeftButtonUp event. 您现在可以使用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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM