WPF ICommand vs RoutedCommand

Let the button have the Command property associated with the user command.

When should I implement ICommand and when should I get out of RoutedCommand ? I see that RoutedCommand implements ICommand .

In this case, I may need to run a ICommand ? What about the MVVM model? Which one is best suited for this purpose?

+44
wpf icommand
Jul 16 '09 at 7:37
source share
2 answers

As you noticed, the RoutedCommand class is an implementation of the ICommand interface, its main difference if its function is similar to:

The Execute and CanExecute methods in 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 cross the tree of elements looking for an object with CommandBinding. CommandBinding-related event handlers contain command logic.

The Execute method raises the PreviewExecuted and Executed events. The CanExecute method raises the PreviewCanExecute and CanExecute events.

In the case where you do not want the RoutedCommand behavior, you will look at your own implementation of ICommand . As for the MVVM pattern, I can’t say that one solution, it seems, each has its own methodology. However, here are a few approaches to this problem that I have encountered:

+62
Jul 16 '09 at 12:34
source share

The only thing I would like to add to Rich McGuire's answer is that RoutedCommands (and their more common descendant RoutedUICommand must be associated with event handlers work correctly.

In most MVVM implementations, I came across an attempt to use binding to ViewModel, and therefore ViewModel (and not View) owns CanExecute / Execute logic.

In contrast, event handlers transfer this load to the view. Processing can then be passed to the ViewModel, but that means a slightly higher degree of connection between the ViewModel and the View (cast + method call, etc.).

+21
Jul 16 '09 at 12:49
source share



All Articles