I am learning MVVM for C# Silverlight development from
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
and I am confused about the RelayCommand class mentioned in the context. The code is:
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion // Fields
#region Constructors
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
#endregion // ICommand Members
}
For which I dont really understand how _execute and _canExecute works in this case. (I am new to C# and even not sure what’s Action and Predicate. I know they are delegates but whats the difference between them and how they works?)
And also, in the program, I didnt get the line
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
Can someone give me a explaination about this, thank you!
A
RelayCommandrequires two pieces of information:_executeaction)_canExecutepredicate)An
Actionis a delegate that represents a method that returnsvoid. In this case the_executeaction takes one parameter (anobject) and returnsvoid.A
Predicateis a delegate that takes a value and returns a boolean result. In this case the_canExecutepredicate takes anobjectvalue and returns abool.Both the
_executeand_canExecutevalues are supplied to theRelayCommandwhen it is constructed because these are the parts of the command that are unique to each individual command.Regarding the
CanExecuteChangedevent:When a subscriber subscribes to the event,
addis called and when they unsubscribe,removeis called. The aboveCanExecuteChangedevent is just a pass-through event (i.e. if a subscriber subscribes to theCanExecuteChangedevent, they automatically subscribe to theCommandManager.RequerySuggestedevent). According to MSDN, theCommandManager.RequerySuggestedevent…I believe that a subscriber would most likely call the
CanExecutemethod on theRelayCommandwhen this event is fired to determine if the command can still be executed.