如何使用WPF中的RelayCommand? [英] How can I use the RelayCommand in wpf?

查看:1248
本文介绍了如何使用WPF中的RelayCommand?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用 RelayCommand 在WPF?

推荐答案

接力命令不存在WPF,它只是提出来突出它在的this~~V MSDN文章。你需要把它写自己,如果你想使用它。

Relay command doesn't exist in WPF, it is just a external class that raised to prominence after it was defined in this MSDN article. You need to write it yourself if you want to use it.

否则,你可以从你这里的WPF工具的委托指令其中有相当多的功能在RelayCommand code一点点。

Otherwise you can you the Delegate command from the WPF toolkit here which has a little bit of extra functionality over the RelayCommand code.


啊,而我打字这个答案改变的问题。假设你正在使用如上述定义,你需要有一个或两个代表提供它的RelayCommand,它返回一个布尔值,它决定了命令是否处于有效的状态下运行,第二个它没有返回值和实际运行命令。如果你不提供CanRun代表则命令将认为它始终处于有效状态。本文中使用的code:

Ah, the question changed while I was typing this answer. Assuming that you are using the RelayCommand as defined above you need to supply it with one or two delegates, one that returns a bool which determines whether the command is in a valid state to be run, and a second which returns nothing and actually runs the command. If you don't supply a "CanRun" delegate then the command will consider that it is always in a valid state. The code used in the article:

RelayCommand _saveCommand;
public ICommand SaveCommand
{
    get
    {
        if (_saveCommand == null)
        {
            _saveCommand = new RelayCommand(param => this.Save(),
                param => this.CanSave );
        }
        return _saveCommand;
    }
}

声明一个RelayCommand触发时将调用Save()方法,并返回CanSave属性作为有效性测试。当这个命令被绑定到WPF中的按钮,按钮的IsEnabled属性将匹配视图模型的CanSave财产,单击按钮时(假设已启用)保存()方法将在视图模型调用。

Declares a RelayCommand that will call the Save() method when triggered and return the CanSave property as a test for validity. When this command is bound to a button in WPF the IsEnabled property of the Button will match the CanSave property of the ViewModel and when the button is clicked (assuming it is enabled) the Save() method will be called on the ViewModel.

这篇关于如何使用WPF中的RelayCommand?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆