While looking at Josh Smith's article about CommandGroup
, I noticed that there are a number of comments on the Internet about how to implement ICommand.CanExecuteChanged
.
A similar question was posted here on StackOverflow, but
For reference:
CommandGroup
uses a simple .NET eventRelayCommand
uses a CommandManager
implementation of CanExecuteChanged
RoutedCommand
uses a CommandManager
implementation of CanExecuteChanged
I am relatively new to WPF, and I would like to know how the CanExecuteChanged
event should have been implemented in Josh Smith's CommandGroup
to avoid any unexpected behaviors or memory leaks?
Josh Smith: Aggregating WPF Commands with CommandGroup
Josh Smith: WPF apps with the MVVM design pattern
StackOverflow: Is Josh Smith's implementation of the RelayCommand flawed?
StackOverflow: comment about CanExecuteChanged
Microsoft: RoutedCommand
PRISM 6: DelegateCommandBase
Lets say you bind a command to a button. When the button is about to be rendered, it would call CanExecute() and based on the result will render either as Enabled or Disabled. WPF automatically calls CanExecute() when "it decides", but you should never relay on this behavior.
Thus, when you implement ICommand, declare a method like UpdateCommand(), which will raise the event in question when You decide. For example, if clicking on a button starts a slow operation which should be triggered again once the previous one has finished, you should raise the event twice - once prior to starting the operation and once after it finishes.
There is no such thing as "the best way to to implement ICommand.CanExecuteChanged". Probably that was part of the reasons not to ship a default implementation of ICommand with the framework. Most MVVM framework, provide default implementations: RelayCommand, ActionCommand, ParameterCommand, AsyncCommand, etc. They just make things easier - pass a delegate and you're ready to go. The Josh Smith's article solves a different issue, a neat way to chain multiple routed command in XAML.
In general:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With