I have a View with multiple Buttons and just as many Commands. For every Command I think I will have to implement ICommand. My program will contain a statemachine, so it will be possible that the CanExecute of the Commands will change run-time.
The only implementation example of the CanExecuteChanged is this:
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
But here it is stated that this implementation is a bad solution. RaiseCanExecuteChanged() should be used.
But I cannot find a proper implementation of the CanExecuteChanged with RaiseCanExecuteChanged. Here I find a basic example, but the user states it
is a very simple implementation (which will probably throw a NullReferenceException occasionally)
I prefer code that doesn't throw exceptions once in a while. Does someone have a better example?
You only need one implementation of the
ICommandinterface.You could take a look at how the
RelayCommandclass is implemented inMvvmLightwhich is a popular but lightweight MVVM library: https://github.com/lbugnion/mvvmlight/blob/master/GalaSoft.MvvmLight/GalaSoft.MvvmLight%20(PCL)/Command/RelayCommand.csIt has a
RaiseCanExecuteChanged()method that simply raises theCanExecuteChangedevent. You should call this method whenever you want to "refresh" the command.You could even download the
MvvmLightassemblies and use theRelayCommandclass directly in your application: https://www.nuget.org/packages/MvvmLight/