C# 如何在 wpf 中使用 RelayCommand?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/862570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use the RelayCommand in wpf?
提问by Sauron
How can I use the RelayCommand
in wpf?
如何RelayCommand
在 wpf 中使用 ?
采纳答案by Martin Harris
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.
Relay 命令在 WPF 中不存在,它只是一个外部类,在这篇 MSDN 文章中定义后,它变得突出。如果你想使用它,你需要自己编写它。
Otherwise you can you the Delegate command from the WPF toolkit herewhich has a little bit of extra functionality over the RelayCommand code.
否则,你可以在你从WPF工具的委托指令在这里其中有超过RelayCommand代码额外的功能一点点。
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,您需要为它提供一个或两个委托,一个返回一个 bool 来确定命令是否处于要运行的有效状态,第二个不返回任何内容并实际运行命令。如果您不提供“CanRun”委托,则该命令将认为它始终处于有效状态。文章中用到的代码:
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.
声明一个 RelayCommand,它将在触发时调用 Save() 方法并返回 CanSave 属性作为有效性测试。当此命令绑定到 WPF 中的按钮时,Button 的 IsEnabled 属性将匹配 ViewModel 的 CanSave 属性,并且当单击该按钮(假设它已启用)时,将在 ViewModel 上调用 Save() 方法。
回答by Luis Perez
As an alternative to creating RelayCommand
wrappers for all your methods can I suggest a free library and source that will allow you to use the binding {BindTo Save()}
. I created it to simplify my bindings. It also makes relative binding much easier. You can find it here: http://www.simplygoodcode.com/2012/08/simpler-wpf-binding.html
作为RelayCommand
为您的所有方法创建包装器的替代方法,我可以建议一个免费的库和源,它允许您使用绑定{BindTo Save()}
。我创建它是为了简化我的绑定。它还使相对绑定更容易。你可以在这里找到它:http: //www.simplygoodcode.com/2012/08/simple-wpf-binding.html