I've been seeing tutorials where people are creating the methods like CanExecute in their code. I'm assuming they are doing this to help the reader understand how it all works. When I look up Command and ICommand it takes me to the ICommand class on MSDN that is used for Windows Store apps. Is there not a Command class for WPF?
The built-in implementation of ICommand
in WPF is RoutedCommand
(and its sibling RoutedUICommand
). RoutedCommand
works like this:
The
Execute
andCanExecute
methods on aRoutedCommand
do not contain the application logic for the command as is the case with a typicalICommand
, but rather, these methods raise events that traverse the element tree looking for an object with aCommandBinding
. The event handlers attached to theCommandBinding
contain the command logic.
The problem with this is that these event handlers must be attached to the code-behind for your view, which is exactly what you do not want to do in MVVM.
Tutorials where you see CanExecute
methods in code (and by that we really mean code outside the ICommand
implementation) are using custom command implementations such as DelegateCommand
and RelayCommand
which are designed to "forward" their CanExecute
/Execute
logic to functions provided on the fly; typically, those are methods on the viewmodel that exposes the command.
These implementations are usually provided by MVVM frameworks (for these two examples the frameworks are Prism and MVVM Light respectively), but they are really simple (both are open source, grab the code and read it) and there's nothing stopping you from copy/pasting the code if you don't want the whole of the framework.
You could summarize the above as "there is built-in a command class in WPF, but it's not really useful in the context of MVVM".
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