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

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

Related

WPF Prism MVVM - Same "Partial View with Command" in one page, how to subscribe the Command?

My project using MVVM design pattern using Prism and Unity, basically following the famous Prism video by Brian Lagunas, but the video didn't mention how to create/use partial view, User Control used in other User Controls.
I'm trying to create custom partial view(UserControl) can be reused in other page (User Control). For example, a View contains a "Browse" button Binding SelectFileCommand and Publish the file Path when done. If I have two of this View in one page, how can I subscribe to the correct command? Both Commands called same name.
For using Partial View:
Register View Type in Module like this:
container.RegisterType<IPartialView, PartialView>();
and use the view directly in page like this:
<views:PartialView DataContext="{Binding PartialViewModel}" />
I'm not sure if this is the correct way to implement Prism MVVM pattern. Please let me know if this is the wrong idea, and how to implement these kind of Partial View.
Thanks a lot.
I'm not sure I understand what you need but I'll give it a try.
If your partial view is in another module, first, you can't use elsewhere than in this same module. You could use some IPartialView, but I'm not sure this is needed here, Prism gives much simpler solutions.
The simplest way to do what I think you want to do would be to have a region where you want to have your partial view. You would use RegisterViewWithRegion in the module definition to register the PartialView against the corresponding region(s).
That way, if you have this partial view several times, you will have several regions with the same name, and only one registration of PartialView in the module. Just give the right DataContext to each region.

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

WPF MVVM - trouble moving things to the view model

I am starting my way with MVVM..
I already implemented a window and need to change it to be mvvm
but.. in my window i have a function that searches the visual tree
how can i do this in my view model? i cannot access a function in the view from viewmodel..
You can create a custom interface that exposes that function and inject its implementation in your ViewModel.
It might not be the most elegant solution, but it is a quick one, (mock-)testable and loosely-coupled.
Please refer to this answer for a well-written example:
How to play Sound and Animations in MVVM
You don't do that in your ViewModel. Accessing the View should be done in the View and if that requires code an option would be to develop a control that contains the code and use the control in the View.
Do not add any knowledge about the View to the ViewModel. That would mess up the pattern and remove (some of) the benefits of MVVM.

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?

Resources