I have a working example of WPF and MVVM, am using control binding to populate controls and have successfully bound a command using RelayCommand. All good. I understand what RelayCommand is for, in that it encapsulates pointers to a predicate to test whether an action can be taken, and a delegate to that action action itself, i.e. enough information for the WPF/MVVM magic glue to know whether to do something in response to a button.
However, I have a couple of questions about RelayCommand. For reference, the code I am using is:
public class RelayCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Predicate<object> _canExecute;
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;
}
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);
}
}
My questions are:
It is completely generic. Why isn't it just a class within .Net somewhere? Everyone is copying the same piece of code and implementing their own. Am I missing something here. I know there is a further RelayCommand for parameterization, but I haven't got that far yet. One step at a time.
Event handler CanExecuteChanged: I have no idea what this does or what it's for. It appears to add handlers to an event that is stored in a static class library. So... if all my ViewModels use RelayCommand, then they will all be assigning events to the same handler? The handler will end up with dozens, or even hundreds of events linked to it? What is this witchery? What assigns to CanExecuteChanged, when and why, and what is it used for?
As a preference, please don't just comment with a link to the Microsoft reference manual for ICommand or the like as (a) they're written as reference for someone who already knows their way round the subject matter well and (b) I've very probably already done my best to understand them. It might get you beans, but it doesn't actually help.
Thanks for any help you can provide.