Question

Is it possible / practical to implement WPF commands as standalone objects? If so, how is this typically done? Most of the examples I see about commanding typically involve using RoutedCommand, RoutedUICommand, or some other implementation of ICommand like RelayCommand. The way these commands work in the MVVM pattern is to expose an instance of one of these types of commands through a property. Inside the ViewModel, the logic for the command is implemented as a method on the ViewModel and then passed as a delegate to the command object.

The "classic" Command pattern as I understand it would be to have each command implemented as it's own standalone object, such as an OpenCustomerViewCommand. Since the logic would be completely encapsulated in its own object, it could potentially be reused in other parts of my app. For example, if I could open the CustomerView from several places in my app it might be helpful to be able to simply create an instance of the OpenCustomerViewCommand on each ViewModel where the CustomerView could be accessed, rather than copy and paste that method into each ViewModel, and pass the delegate to a RelayCommand. If I understand correctly, the predefined ApplicationCommands such as Cut and Paste behave this way.

To me, having to provide the logic inside the ViewModel seems to diminish the value of the command pattern a bit. I suppose I don't really understand the major difference between doing it this way, and having a code behind that implements command handlers for UI events. Is there any reason I should be using the RoutedCommand pattern over the more classic approach I described above?

Was it helpful?

Solution

You could do this, but it requires some method of routing the request appropriately.

In your example, provided the OpenCustomerViewCommand knows how and where to open the "Customer View", you could easily reuse this anywhere. Instead of using a class like RelayCommand, you can just implement ICommand directly and add your logic to do this.

The problem, however, is that most commands tend to be more of an adapter for xaml to execute ViewModel-specific functionality. In most applications on which I've worked, there tend to be few commands that really need the reuse - most commands are tied to functionality specific to the ViewModel in question. As such, something like RelayCommand makes hooking this up fairly easy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top