Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Commands in MVVM

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?

like image 619
pallasmedia Avatar asked Mar 06 '13 13:03

pallasmedia


1 Answers

The built-in implementation of ICommand in WPF is RoutedCommand (and its sibling RoutedUICommand). RoutedCommand works like this:

The Execute and CanExecute methods on a RoutedCommand do not contain the application logic for the command as is the case with a typical ICommand, but rather, these methods raise events that traverse the element tree looking for an object with a CommandBinding. The event handlers attached to the CommandBinding 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".

like image 79
Jon Avatar answered Sep 28 '22 22:09

Jon