Reputation: 23
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.
How to correctly implement CanExecute?
I have just been returning true, but I know there is a proper way to handle it. Maybe
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
}
}
Upvotes: 2
Views: 10697
Reputation: 707
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();
}
Upvotes: 3
Reputation: 1798
http://www.identitymine.com/forward/2009/09/using-relaycommands-in-silverlight-and-wpf/
http://matthamilton.net/commandbindings-with-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);
Upvotes: -2