Proper implementation of CanExecuteChanged

968 views Asked by At

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?

1

There are 1 answers

0
mm8 On

You only need one implementation of the ICommand interface.

You could take a look at how the RelayCommand class is implemented in MvvmLight which is a popular but lightweight MVVM library: https://github.com/lbugnion/mvvmlight/blob/master/GalaSoft.MvvmLight/GalaSoft.MvvmLight%20(PCL)/Command/RelayCommand.cs

It has a RaiseCanExecuteChanged() method that simply raises the CanExecuteChanged event. You should call this method whenever you want to "refresh" the command.

You could even download the MvvmLight assemblies and use the RelayCommand class directly in your application: https://www.nuget.org/packages/MvvmLight/