CanExecute does not get called for your ICommand implementation?
December 11, 2009If you have worked with RoutedCommand objects in WPF, you are probably used to the “magic” ways, WPF uses to figure out when CanExecute handlers should be called to enable or disable your commands. This usually happens when interaction in the UI has happened, like change of focus or change of selection in lists.
If you switch to a custom implementation of the ICommand interface, you will soon experience the problem that the CanExecute method does not get called in the same way as for RoutedCommand objects. That’s because this behavior is built into WPF’s RoutedCommand objects and there is now way for WPF to figure this out for generic ICommand implementations.
But adding the simple piece of code below does the trick, and this is how it works: If WPF hooks up an event handler for CanExecuteChanged (part of the ICommand interface), we use this same event handler and hook it up to the RequerySuggested event of the CommandManager class. This event gets fired whenever UI interaction (like focus or selection change) happens and automatically the hooked up handler method for CanExecuteChanged gets called, which causes our implementation of the CanExecute method to get evaluated … finally.
public
event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public bool CanExecute(object parameter) { . . . }