Can a ViewModel talk to View in MVVM pattern? - wpf

In MVP pattern, a Presenter has an interface of View so the presenter can call iview.DoSomething().. What about in MVVM pattern?
According to John Gossman's UML diagram http://blogs.msdn.com/johngossman/archive/2006/04/13/576163.aspx , ViewModel doesn't have an interface of View. So, seems like the ViewModel and View should be communicated via Binding only. (or use attached property or blend behavior or etc).
What do you guys think?

I agree with John Gossman. The way the ViewModel "talks" to the View is through Bindings only. In fact - the ViewModel shouldn't care about the View at all. It should simply make data available through properties, and it's up to the View to decide what it will dynamically bind to in the ViewModels. If the ViewModel wants to tell the View something this should occur implicit through Bindings.
A similar question was asked an hour ago - here.

The whole purpose of MVVM is to vastly reduce the amount of code in your code-behind class of your WPF form or user control. The idea is that anything that would be handled by the view in classic MVC/MVP can be translated over to the VM by using a combination of data binding and/or commands. In my general usage of MVVM I have managed to completely remove all of the code-behind in my forms/user controls and the VM has no direct knowledge of the view it is controlling. If you have a situation that really cant be handled by data binding or a command then please elaborate on your initial question and I (or one of the many, many more talented MVVM'ers on here) will try to point you in the right direction.

It typically does - through events on INotifyProperty changed, if nothing else.

Can a ViewModel talk to View in MVVM pattern?
Yes, but in a decoupled way. It’s allowed to introduce an interface IView for the communication.
The MVVM pattern is about to move the logic from the View into the ViewModel. This way we are able to unit test this logic.

Related

MVVM With Silverlight

I have been downloading a lot of example code to help me gain a better understanding of MVVM within silverlight.
One of the things I have noticed is an inconsistency within the sample code I have downloaded. Some for example implement INotifyPropertyChanged on the viewmodels, where others implement it on the Model.
Which is the preferred way of handling property changes, should it be handled at the model level or the viewmodel level?
Handling (Notifying) property changes in the viewmodel would seem more natural if this is to update the item that's being displayed in the view by databinding.
One of the reasons for having a viewmodel in the first place is that it holds the data from the model in such a way that it's easy for the view to bind to it.
So, if the main reason for your INotifyPropertyChange in is to update the item which is bound in the view, you should update it in the viewmodel.
I typically use DependencyProperty instead of INotifyPropertyChanged, but the idea is the same.
Their purpose is to notify the view controls, they are bound to, that they have changed so the view can update. This implies a weak connection between the view and whatever holds the property or object. In MVVM, the view should never have any link to the model because of separation of concerns.
I will often have physically force this by creating a separate project for each of the view, viewmodel, and model. So, the answer to your question is that the INotifyPropertyChanged should be implemented at the viewmodel level because the view should never touch anything from the model level. Having said this, MVVM is just a coding paradigm to make the programmers job easier, so there could be reasons to implement it differently if it means making your job easier and it doesn't having any negative consequences.

Matching implementations to parts of the pattern

While trying to understand the MVVM pattern I came across this video linked from the MVVM Light Toolkit website.
In TechDays 2010 - Laurent Bugnion states the WPF/Silverlight both use MVVM pattern for their structure. Can someone please clarify which components in WPF/SL (which Bugnion named specifically and are listed below) are the Model, ViewModel, and View?
These are the three items he stated as being a part of the MVVM pattern:
Code
Dependency Properties
Control Templates (Data Templates?)
I am the first to admit that this is a little bit stretched ;) but let me clarify. The statement was made to illustrate that MVVM is a very natural pattern in SL/WPF (and all other frameworks that use XAML and databinding). In the example, I was talking about the separation of concerns between the control's code (not referring to "code" in general, but specifically to a control's code, for example a Button class) and its template. In this illustration, the code acts like a ViewModel, i.e. it drives the view. The template is more obviously the View. And the glue between those is the databinding which is enabled through Dependency Properties.
When I say it is a bit of a stretch, we can see that there is no Model in this analogy. Also, the mechanism binding a control's view to its viewmodel (code) is a little more complex than just DPs and bindings. There are also naming conventions added to that.
In retrospect, I guess I could have been clearer, and I pushed this analogy a bit too far. I guess the main point I would like you to take from this is: In SL/WPF, code and view are loosely coupled through databinding. This is true for basic controls, and you can also structure your application in a loosely coupled manner, with the help of databindings.
I hope it makes a little more sense now ;)
Cheers,
Laurent
I haven't watched the video. Definitely the control templates and data templates are your views. The dependency properties are really also part of your view, but can be bound to data in a class which serves as a model for the view, i.e. the view-model. The "code" he's referring to must be the business logic which is your model.
I would think of it as three objects. You have a view object, like a TextBox control which has styling applied to it in the form of other view objects that comprise the templates. The TextBox also has dependency properties which are objects that can bind (synchronize) a value on the TextBox to a value on another object. That object is the DataContext of the TextBox, which is your view-model object. The view-model object can be thought of as an adapter for a model to support the specific needs of the view.
The Model represents the data and business logic. It should represent your business
(domain) and it should not be aware by anyway of your UI.
The View this is the UI – the bridge between your software and its users. Normally
the View is only aware of the ViewModel but there might be cases in which it may make
sense to expose the Model directly to it. So your XAML for UI like Grid, Button,
DataTemplate,Style, control Template etc can be found here.
The ViewModel: this is the way you connect your model to a specific View. See it has
code that massages your Models in a way that the View can consume. The ViewModel should be
View agnostic as the Model should. So the communication between View and ViewModel is
purely based on DataBinding. When you are dealing with MVVM pattern the use Dependency
property will be bare minimum. for example when you are creating any Custom control at
that time you have to use the Dependency property for the supporting the binding.
three items he stated as being a part of the MVVM pattern
There is a flaw in this. These things are not parts of MVVM; they enable MVVM. Parts of MVVM are Model, View and ViewModel. To call 'code' a part of MVVM or to call it a part of the ViewModel is oversimplifying and useless.
There is code in the Listbox control; it wouldn't function if there weren't.
Of course, code in the View is frowned upon while others say it is very well possible.
When trying to understand MVVM focus on the responsibilities of the Model, ViewModel and View and do not worry too much about code, dependency properties and Control Templates. You cannot map these to MVVM.

Choosing between bound ViewModel properties or messaging to communicate between ViewModel and View using the MVVM Light Toolkit

I'm using MVVM Light toolkit (which I love). I currently have messaging in place for some interaction originating from the ViewModel and intended for consumption by the View. Typically these types of messages indicate the View should do something like hide itself, show a confirmation message that data was saved, etc.
This works. In the constructor for the View, I register with the Messenger:
Messenger.Default.Register<NotificationMessage<PaperNotification>>(this, n => HandlePaperNotification(n));
When I'm using the Messenger to communicate cross-cutting concerns between ViewModels (like identity), I can see that when the ViewModel is cleaned up in the ViewModelLocator, the base class for ViewModels (ViewModelBase) unregisters any subscribed messages. I don't have to do anything, as MVVM Light Toolkit handles that for me. However, when I use them in the Views, I have to expressly unregister them at Closing time, like so:
Messenger.Default.Unregister(this);
I suppose I could implement a base class for Views to inherit from.
However, it strikes me that perhaps this is a code smell to be using the Messenger in the View... it works, but it might not be the best way. I'm wondering if I should instead create a property on the ViewModel and bind whatever part of the View's elements to it. In the example of hiding a form, a property could be a boolean called "Show". As I think about it, I can see that in many cases this will result in having to write a ValueConverter. One way seems less testable. The other way seems to require much more code and perhaps the introduction of excess ValueConverters, which could become a code smell in themselves.
So (after all that build up) my question is this:
Is it preferable to use messages within the View or is it better to add properties (and potentially ValueConverters) to allow the ViewModel to drive it in a more bindable fashion?
In MVVM. ViewModel comunicates with View through DataBinding and Commands. If you need some other functionality, you need to implement it using this means.
Messaging is supposed to be only for ViewModels. Views are supposed to be "stupid" visualisers of your data in ViewModel.
The Messaging logic in MVVM Light is there for communication between ViewModels. I've never run into any communication between View and ViewModel that I couldn't solve with binding and/or commands. Sometimes I need Value Converters and sometimes I need code in the code-behind, but I've never had to make the ViewModel directly push data to the View.
This is an interesting discussion and I found this thread when I was wondering about view model to view communication. Interestingly, MVVMLight's creator seems to find it perfectly acceptable to send messages from a view model to a view. Another example of differing opinions about what is a good MVVM design.

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