I have a View with multiple Button
s and just as many Command
s. 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
ICommand
interface.You could take a look at how the
RelayCommand
class is implemented inMvvmLight
which 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 theCanExecuteChanged
event. You should call this method whenever you want to "refresh" the command.You could even download the
MvvmLight
assemblies and use theRelayCommand
class directly in your application: https://www.nuget.org/packages/MvvmLight/