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

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

问题描述

如何在 wpf 中使用 RelayCommand?

解决方案

Relay 命令在 WPF 中不存在,它只是一个外部类,在 这篇 MSDN 文章.想用就得自己写.

否则,您可以在 此处使用 WPF 工具包中的 Delegate 命令.a> 与 RelayCommand 代码相比,它有一些额外的功能.

<小时>

啊,当我输入这个答案时,问题发生了变化.假设您正在使用上面定义的 RelayCommand,您需要为它提供一个或两个委托,一个返回一个 bool 来确定命令是否处于要运行的有效状态,第二个不返回任何内容并实际运行命令.如果您不提供CanRun"委托,则该命令将认为它始终处于有效状态.文章中用到的代码:

RelayCommand _saveCommand;公共 ICommand 保存命令{得到{如果(_saveCommand == null){_saveCommand = new RelayCommand(param => this.Save(),参数 =>this.CanSave );}返回 _saveCommand;}}

声明一个 RelayCommand,它在触发时调用 Save() 方法并返回 CanSave 属性作为有效性测试.当此命令绑定到 WPF 中的按钮时,该按钮的 IsEnabled 属性将匹配 ViewModel 的 CanSave 属性,并且当单击该按钮(假设它已启用)时,将在 ViewModel 上调用 Save() 方法.

How can I use the RelayCommand in wpf?

解决方案

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.

Otherwise you can you the Delegate command from the WPF toolkit here which has a little bit of extra functionality over the RelayCommand 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;
    }
}

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天全站免登陆