WPF ViewModel Commands CanExecute issue

To complete Will’s answer, here’s a “standard” implementation of the CanExecuteChanged event : public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } (from Josh Smith’s RelayCommand class) By the way, you should probably consider using RelayCommand or DelegateCommand : you’ll quickly get tired of creating new … Read more

CanExecuteChanged event of ICommand

This event is raised by the command to notify it’s consumers (i.e. Button, MenuItem) that it’s CanExecute property may have changed. So if focus is moved from one TextBox to another, your command may need to be enabled/disabled. This information also needs to be passed to any controls using your command. In general, this event … Read more

CommandManager.InvalidateRequerySuggested() isn’t fast enough. What can I do?

CommandManager.InvalidateRequerySuggested() tries to validate all commands, which is totally ineffective (and in your case slow) – on every change, you are asking every command to recheck its CanExecute()! You’d need the command to know on which objects and properties is its CanExecute dependent, and suggest requery only when they change. That way, if you change … Read more

Is Josh Smith’s implementation of the RelayCommand flawed?

I’ve found the answer in Josh’s comment on his “Understanding Routed Commands” article: […] you have to use the WeakEvent pattern in your CanExecuteChanged event. This is because visual elements will hook that event, and since the command object might never be garbage collected until the app shuts down, there is a very real potential … Read more

What is the actual task of CanExecuteChanged and CommandManager.RequerySuggested?

CanExecuteChanged notifies any command sources (like a Button or MenuItem) that are bound to that ICommand that the value returned by CanExecute has changed. Command sources care about this because they generally need to update their status accordingly (eg. a Button will disable itself if CanExecute() returns false). The CommandManager.RequerySuggested event is raised whenever the … Read more

ICommand MVVM implementation

This is almost identical to how Karl Shifflet demonstrated a RelayCommand, where Execute fires a predetermined Action<T>. A top-notch solution, if you ask me. public class RelayCommand : ICommand { private readonly Predicate<object> _canExecute; private readonly Action<object> _execute; public RelayCommand(Predicate<object> canExecute, Action<object> execute) { _canExecute = canExecute; _execute = execute; } public event EventHandler CanExecuteChanged … Read more