wpf 为 MVVM Light ICommand 正确使用 CanExecute
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17222802/
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
Correctly Using CanExecute for MVVM Light ICommand
提问by togglebutton
I am starting to learn MVVM in C# and I was wondering how to correctly use the CanExecute method for an ICommand in MVVM Light. My WPF application is in VS 2012 C# 4.5 framework.
我开始在 C# 中学习 MVVM,我想知道如何在 MVVM Light 中为 ICommand 正确使用 CanExecute 方法。我的 WPF 应用程序在 VS 2012 C# 4.5 框架中。
How to correctly implement CanExecute?
如何正确实现 CanExecute?
I have just been returning true, but I know there is a proper way to handle it. Maybe
我刚刚返回 true,但我知道有一种正确的方法来处理它。也许
if(parameter != null)
{
return true;
}
Here is some of the sample code.
这是一些示例代码。
private RelayCommand sendCommand;
public ICommand SendCommand
{
get
{
if (sendCommand == null)
sendCommand = new RelayCommand(p => SendStuffMethod(p), p => CanSendStuff(p));
return sendCommand;
}
}
private bool CanSendStuff(object parameter)
{
return true;
}
private void SendStuffMethod(object parameter)
{
string[] samples = (string[])parameter;
foreach(var sample in samples)
{
//Execute Stuff
}
}
采纳答案by KeyboardFriendly
http://www.identitymine.com/forward/2009/09/using-relaycommands-in-silverlight-and-wpf/
http://www.identitymine.com/forward/2009/09/using-relaycommands-in-silverlight-and-wpf/
http://matthamilton.net/commandbindings-with-mvvm
http://matthamilton.net/commandbindings-with-mvvm
http://www.c-sharpcorner.com/UploadFile/1a81c5/a-simple-wpf-application-implementing-mvvm/
http://www.c-sharpcorner.com/UploadFile/1a81c5/a-simple-wpf-application-implementing-mvvm/
bool CanSendStuff(object parameter);
//
// Summary:
// Defines the method to be called when the command is invoked.
//
// Parameters:
// parameter:
// Data used by the command. If the command does not require data to be passed,
// this object can be set to null.
void Execute(object parameter);
回答by Saykor
Declare command
声明命令
public ICommand SaveCommand { get; set; }
In constructor:
在构造函数中:
public SelectedOrderViewModel()
{
SaveCommand = new RelayCommand(ExecuteSaveCommand, CanExecuteSaveCommand);
}
Methods:
方法:
private bool CanExecuteSaveCommand()
{
return SelectedOrder.ContactName != null;
}
private void ExecuteSaveCommand()
{
Save();
}

