Initial problem:
I'm using the typical RelayCommand
implementation in my MVVM Application.
I realized that the CanExecute
of my RelayCommand
is not always called even if meaningful properties of my ViewModel have changed.
I read that we can manually call CommandManager.InvalidateRequerySuggested
to raise a RequerySuggested
event. This will eventually make the Command Source call the CanExecute
method.
RequerySuggested
is automatically raised by the CommandManager
when some UI events occurs. I feel like it would be useful if it would also be raised on PropertyChanged
.
My current solution:
I modified the property changed method of my ViewModelBase
class like this:
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
Application.Current.Dispatcher?.Invoke(CommandManager.InvalidateRequerySuggested);
}
Concerns:
I have not found any ViewModelBase
online implemented this way and I feel like this should be a red flag.
RelayCommand
is highly recommended in MVVM for it's simplicity so I find weird that I end up having to manually call the CommandManager. Why not preferring DelegateCommand
then?
I know that this causes the CanExecute
to be called more often, but it is already spammed every time a UI event happens anyway.