I am reading Josh Smith’ WPF Apps With The Model-View-ViewModel Design Pattern tutorial
i don’t understand what the below code is trying to do.
First, the syntax reminds me properties, but with add/remove instead.
But what is CommandManager.RequerySuggested?
It delegates the event subscription to
the CommandManager.RequerySuggested
event. This ensures that the WPF
commanding infrastructure asks all
RelayCommand objects if they can
execute whenever it asks the built-in
commands
//Figure 3 The RelayCommand Class
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 }
Also, save command is configured with lambdas. 1st, there are 2 param variables.
Will they conflict? i cannot just do something like RelayCommand(this.Save(), this.CanSave) or is there no such syntax.
_saveCommand = new RelayCommand(param => this.Save(),
param => this.CanSave );
CommandManager.RequerySuggested += valuemeans that if the function forCanExecutecan resolve to bothtrueandfalsedepending on some conditions.WPF will disable the
Button/MenuItem(CommandButtonBase) if it evaluates tofalseand enable whenever the condition evaluates totrue.If you don’t have those two lines, WPF will ask the command only once (when the Button/MenuItem is loaded and will not update after that unless you do it manually.
The two parameters (lambda-expressions) are of type
Action<object>and aPredicate<object>respectively. So, they cannot, by definition, conflict (paramsis just a name – and as the two functions have different scope – they don’t conflict).If you have a method with the right signature, you can use that in the constructor
private void Save(object obj)and
private bool CanSave(object obj)respectively, but you shouldn’t have the
()at the end – so newRelayCommand(this.Save,this.CanSave)should work.