Why favor RelayCommand over RoutedCommand? - wpf

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?

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.

Related

Is there a better way than handling CommandBindings in code behind?

I have an application using MVVM. I'm trying to Intercept key presses on an MCE Remote control for Play, Pause, Stop etc....
Currently I'm using command bindings with a method in the code behind performing the related action on a media element as such
<Window.CommandBindings>
<CommandBinding Command="MediaCommands.Play" Executed="PlayMediaElement"/>
<CommandBinding Command="MediaCommands.Stop" Executed="StopMediaElement"/>
</Window.CommandBindings>
Before trying to include the remote control functionality I had approx 10 view-models/views with nothing in code behind.
I'm wondering if there is a better way to do this so I retain the MVVM pattern or is it perfectly acceptable/preferable to implement in this way.
EDIT - I've moved the Command Bindings from a UserControl inside a View into my MainWindow.xaml and placed the methods into MainWindow.xaml.cs. MainWindow doesn't have a view/viewmodel relationship, simply a content control with a ViewModel linked to it.
In my code behind methods I'm making use of a Mediator to send messages (Play,Pause,Stop etc...) to my mediaplayerviewmodel which in turn interacts with it's respective view. Is this a good idea or is there a better way?
I think Josh Smith created a huge confusion in his 2009 article, when he made a point that his code-behind CS files remained mostly empty. MVVM is not about not having code-behind. It is about separation of concerns. If there is any practical rule you should follow, is to make the ViewModel view agnostic (i.e. no reference from the ViewModel to the View. Think having a second unit test implementation of a 'View' for your ViewModel).
This "no code behind" confusion caused very odd structures just to work arround a problem that shouldn't have existed to begin with.
Having code behind in the MainWindow.xaml.cs is perfectly reasonable solution, as long as you don't have logic there, but simply forward the call to an appropriate method in the View Model. If that was my code I would have created custom commands (a la DelegateCommand from the same article) that binds directly to commands in the ViewModel, but your design is 100% legit as well.
Head over to Codeplex.com and look for Caliburn (or better Caliburn Micro). It extends WPF to actually allow calling of methods with arbitrary parameters pulled from other objects and the method being in the view model / controller without having a "hook method" in code behind just fowwarding the call.
The extensions can do wonderfull thignsl ike pull the value of a textbox and pass it as parameter to a method, then react on the return value - much like a view should.
You run in a limitation of "stock" wpf - which simply can only point towards method handlers in code behind without any regards to parameters. Alterantives exist, even from microsoft.

Standalone Command Objects in WPF

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?
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.

wpf mvvm confusion

as per my understanding about mvvm is.
there is a model (entity class that also implement inotify...), view (xaml code) and some class as vm (kind of controller which normally inherit icommand) to let us make events/commands to be generated on specific event...
m just wondering about difference between viewmodel class and xaml's code behind class... why don't we simply consider and enhance code behind...
no considerable reason is in my mind to justify this...
or kindly write somethng with example to clear mvvm... and why mvc or mvp is hell for wpf app????
The Model does not implement INotifyPropertyChanged, the ViewModel does. The actual WPF view data-binds to the ViewModel. There is now a lot of documentation online for this.
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
MVVM is identical to Fowler's
Presentation Model, in that both
patterns feature an abstraction of a
View, which contains a View's state
and behavior.
http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx
In practice however, only a small
subset of application UI can be data
bound directly to the Model,
especially if the Model is a
pre-existing class or data schema over
which the application developer has no
control. The Model is very likely to
have a data types that cannot be
mapped directly to controls. The UI
may want to perform complex operations
that must be implemented in code which
doesn't make sense in our strict
definition of the View but are too
specific to be included in the Model
(or didn't come with the pre-existing
model). Finally we need a place to
put view state such as selection or
modes. The ViewModel is responsible
for these tasks. The term means
"Model of a View", and can be thought
of as abstraction of the view, but it
also provides a specialization of the
Model that the View can use for
data-binding. In this latter role the
ViewModel contains data-transformers
that convert Model types into View
types, and it contains Commands the
View can use to interact with the
Model.
MVVM is associated with WPF because WPF's data binding mechanism when combined with this pattern makes testable GUIs a breeze.
Check this two videos to get some idea. Both videos show developing application starting with everything in code behind and then they refactor to MVVM pattern.
Mike Taulty's series of videos (in fact there is 10 videos in total, check at least first and second)
Jason Dolinger on Model-View-ViewModel
Also, see this SO question for more links: MVVM: Tutorial from start to finish?
why don't we simply consider and enhance code behind...
(In addition to what other have already mentioned:) because it make your code easier to read. In the code behind file, you have UI stuff that is impossible or to complicated to do in XAML. In the view model code file, you have everything related to filling your form with data.
As with all design patterns, blindly following it is not the best idea. For very small windows, MVVM might not make sense. For larger windows, MVVM forces you to make a separation of concerns, which will usually make both your code behind file and your MVVM class easier to read, to understand and to debug.
First, for MVVM purposes you don't need the VM to inherit ICommand. Instead, VM contains a set of properties of type inherited from ICommand. So that View just binds to those properties. F.i.:
<Button Command="{Binding DoSomethingCommand}" />
And code-behind isn't used because it's basically inseparable part of the View. It's the same class your View is. You can't easily test it, and your code is often tightly coupled to the XAML.
And Model is not really obliged to (but can) support INotifyPropertyChanged. Whereas ViewModel should of course implement this interface to allow binding.
I suggest you to read a few introducing articles on the subject. It's not that confusing. This can be the first one: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
why don't we simply consider and enhance code behind...
Code behind is often (always?) the simplest approach...if you're a developer. But MVVM is designed to assist more than just a developer. MVVM is for the database girl and the graphics guy too.
Separating M (for the db) and V (for the artist) and VM (for you) allows each person to work independently of each other. So, for example, you don't have to wait for the graphics guy to make a UI before you can wire up the db. You can all work in parallel (in theory).
Separation of concerns means separate jobs.

WPF: Binding with nonstatic parameter? (newbie question)

This will probably be obvious but I can't find the best way.
I want to show the user's ToDo's in a listbox. These ToDo's are in the database and consist of an Id, UserId and Description.
The user logged in to the app.
How can I retrieve the ToDo's for that certain userId and set it up for binding to the listbox?
I was trying with an ObjectDataProvider but I cant figure out how to use that in combination with nonstatic stuff (like my _dbService, userId, language, ...).
Are the only options to make all those things static versus binding in the code behind?
If so, this means that ObjectDataProvider isn't very useful, no?
I find a lot of examples of it being used with a hardcoded parameter but I hardly see any situation where I'd need such a functionality..
I do all my WPF using the Model-View-ViewModel pattern. I've given you one link there but Google will give you loads. MVVM seems to be the standard pattern for WPF. This project is probably more complicated than you need but it is well-written and brings home the use of MVVM.
Basically, you create a Model of your data. In this case, you'd probably create a simple class (I'll call it ToDoItem) with properties Id, UserID and Description. Use your preferred mechanism to get a collection of these from the database. Link to SQL, Entity Framework, a standard query, whatever.
Then you have your ViewModel - you have an instance of the ViewModel for each instance of the Model: the VM has a reference to the M and 'forwards' properties to it. The ViewModel is what you use to manipulate the model.
Then you have your View - this is the UI. You set the DataContext of the View to be the ViewModel and then your bindings automatically bind to the ViewModel. Your View just ends up being the things you can see. All of the work gets done in the ViewModel. This means it's very easy to test.
So, when you click on a button in your View, the bindings pass this onto a Command in your ViewModel which manipulates the Model.
The UI is also a View with a ViewModel. So, your UI VM might load a collection of Models from the database and stick them in an ObservableCollection. The ListBox items collection would be bound to this ObservableCollection.
It's hard to explain all of this in a post like this. Read a couple of articles and see what you think. I'm still quite new at this, too, but I believe my reading about MVVM has paid off.
Hela Thomas, Tom here from Orbit One :)
MVVM is the way to go. I'm on my 4th project and WPF really shines if you use mvvm. You already tried MVC (or MVP as we did on recy*tyre) and that's a nice separation of concern.
MVVM takes it a step further since the viewmodel knows absolutely nothing about the view.
The view binds to the viewmodel, so it has a reference to it (2 way, super powerful and works beyond the typical MS demo). The viewmodel is just a poco and is a representation of your view, data + behaviour. Once you dig this paragraph the cool term mvvm will have no secrets.
I see if I can come up with a small demo. Maybe I'll have time later.
What I will come up with is a view (xaml, file 1) that binds to a viewmodel (file 2, a poco class, not to be mistaken with code behind). The model can be whatever you like (service layer or directly to the repositories). Using the power of 2 way binding we will bind to an observable collection meaning that if we add/delete/... something to the collection the view will pick it up without us putting energy into it.
My first 2 wpf projects was done with Caliburn Micro (see codeplex) which is a powerful framework based on conventions. It shields you away from hardcore wpf (creating tour dependency properties yourself mainly) and you can create something relatively fast without fully understanding wpf. That's a downside of itself but it worked for me. As of project 3 I started taming those dependency properties myself and it will make you a better wpf developer.
I see the question is from October.. did you find a good solution?

Josh Smith's CommandViewModel in MVVM, what's the point?

I was looking through Josh Smith's MVVM Example and I noticed he defines a basic view model called CommandViewModel, and looking through his demo app, I just can't see the point of it.
As far as I can tell, the CommandViewModel just represents a command that the user can perform. A collection of these view models is used to render a set of commands, similar to a tool bar or shortcut list.
My impression is that it is a view model whose sole concern is a single command. I suppose this allows you to not only encapsulate the command but also other bindable, relevant things such as Name, but also potentially other UI stuff related to the command (tooltip, etc).

Resources