Search code examples
wpfmvvm

Why favor RelayCommand over RoutedCommand?


I'm trying to learn the MVVM software design pattern. I've got Matthew MacDonald's book, "Pro WPF in C# 2010" to learn WPF better. In trying to start learning MVVM I've looked at the WindowsClient.net website, especially Todd Miranda's video, "How Do I: Build Data-driven WPF Application using the MVVM pattern". In that he discusses briefly the RoutedCommand, but writes his own implementation of a class called RelayCommand based upon the ICommand interface.

This looked promising, but I've got a problem in that the window I'm developing (a simple window with textboxes, and button to issue a search using the parameters entered by the user and returning results in a listbox) is more complicated than what Todd did. Basically, I can't find a way to get the search parameters entered by the user in the RelayCommand class I've written which returns an ObservableCollection I call AllClients (that gets displayed in the listbox).

MacDonald's book discusses the RoutedCommand and especially the RoutedUICommand, and frankly this looks various promising to what I'm trying to do. However, again in an effort to better understand the MVVM pattern I've taken a quick look at what books might be available to help learn the MVVM pattern on Amazon and found some books like, "Pro WPF and Silverlight MVVM" by Gary Hall. In that book Hall seems to strongly suggest that the RoutedCommand route is not the way to go. That it is problematic and therefore it is better to use the RelayCommand.

Well, frankly, I'm really confused. First, I don't understand Hall's argument at all. Why is using RoutedCommands (or presumably RoutedUICommands as well) such a bad alternative? Why is using RelayCommands so superior?


Solution

  • Generally speaking, I have found that RoutedCommand is often oversized. There is a good explanation of its power in WPF ICommand vs RoutedCommand.

    The superiority of RelayCommand, I think, comes from its ease of use and straightforwardness. It is instantiated with just an Executeand optionally a CanExecute event handler in the view model. This has always been just fine in situations where I just wanted to hook up some functionality to a button, menu item and the like.

    If you have any parameters you need to pass the command, I would suggest having them in your view model, next to where the command implementation is located. For a search command, for instance, you would have a text box bound to a string property in your view model that contained the search text. When your command's Execute event handler is invoked, it would take that property's value and pass it to the search routine you have implemented in your model. I thus don't see a need to use the Parameters property of a command. The view model approach is just more flexible and allows for multiple parameters.