How can WPF Converters be used in an MVVM pattern? - wpf

Let's say I have a View that is bound to ViewModel A which has an observable collection Customers.
An advantage of this MVVM pattern is that I can also bind the View to ViewModel B which fills it with different data.
But what if in my View converter Converters to display my customers, e.g. I have a "ContractToCustomerConverter" that accepts a Contract and returns the appropriate Customer to be displayed.
The problem with this is that the converter exists outside the MVVM pattern and thus doesn't know that my ViewModel has another source for customers.
is there a way for the View to pass the ViewModel into the Converter so that it participates in the decoupling that the MVVM pattern provides?
is there a way for me to somehow include the Converter in my ViewModel so that the converter uses the current dependencies which ViewModel has available?
or are converters just glorified code-behind and thus not used in the MVVM pattern, so if you are using MVVM then you just create your own "converters" (methods on your ViewModel class) which return things like Image objects, Visibility objects, FlowDocuments, etc. to be used on the view, instead of using converters at all?
(I came upon these questions after seeing the use of Converters in the WPF demo application that comes with the MVVM Template Toolkit download, see the "Messenger Sample" after unpacking it.)

I usually don't use converters at all in MVVM, except for pure UI tasks (like BooleanToVisibilityConverter for instance). IMHO you should rather declare a Customer property of type CustomerViewModel in your ContractViewModel, rather than use a ContractToCustomerConverter

In this conversation there is a comment that agrees with Kent's position, not to use Converters at all, interesting:
A ViewModel is basically a value converter on steroids. It takes "raw" data
and converts it into something presentation-friendly, and vice-versa. If
you ever find yourself binding an element's property to a ViewModel's
property, and you're using a value converter, stop! Why not just create a
property on the ViewModel that exposes the "formatted" data, and then drop
the value converter altogether?
And in this conversation:
The only place I can see a use for
value converters in an MVVM
architecture is cross-element
bindings. If I'm binding the
Visibility of a panel to the IsChecked
of a CheckBox, then I will need to use
the BooleanToVisibilityConverter.

Converters should rarely be used with MVVM. In fact, I strive not to use them at all. The VM should be doing everything the view needs to get its job done. If the view needs a Customer based on a Contract, there should be a Customer property on the VM that is updated by VM logic whenever the Contract changes.
An advantage of this MVVM pattern is that I can also bind the View to ViewModel B which fills it with different data.
I dispute that claim. In my experience, views are not shared across different VM types, and nor is that a goal of MVVM.

For those effectively saying no "non-trivial converters" in the view, how do you handle the following?
Let's say that I have a Model of climate sensors that represents time series of readings from various instruments (barometer, hygrometer, thermometer, etc.) at a given location.
Let's say that my View Model exposes an observable collection of the sensors from my Model.
I have a View containing a WPF Toolkit DataGrid that binds to the View Model with the ItemsSource property set to observable collection of sensors. How do I represent the view of each instrument for a given sensor? By displaying a small graph (think Edward Tufte sparkline here) that is generated by converting the time series to an image source using a converter (TimeSeriesToSparklineConverter)
Here is how I think of MVVM: The Model exposes data to View Models. The View Model exposes behavior, Model data and state to View. Views do the job of representing Model data visually and providing an interface to behaviors consistent with the View Model state.
Thusly, I don't believe that the sparkline images go in the Model (the Model is data, not a particular visual representation of it). Nor do I believe that the sparkline images go in the View Model (what if my View wants to represent the data differently, say as a grid row just showing min, max, average, standard deviation etc. of the series?). Thus, it seems to me that the View should handle the job of transforming the data into the desired representation.
So if I want to expose the behaviors, Model data and given state for a certain View Model in a command-line interface instead of a WPF GUI, I don't want my Model nor my View Model containing images. Is this wrong? Are we to have a SensorCollectionGUIViewModel and a SensorCollectionCommandLineViewModel? That seems wrong to me: I think of the View Model as an abstract representation of the view, not concrete and tied to a particular technolgy as these names suggest they are.
That's where I am in my continually evolving understanding of MVVM. So for those saying not to use converters, what are you doing here?

I've been using Stackoverflow for years and this is accrual my first answer posted.
I think converters belongs to View in MVVM, consider the following situation:
App is developed by 3 teams, webapi team, webclient team and UI team. UI changed frequently so the webclient team (which receives data from webapi and put them into viewmodel) cannot always modify the viewmodel to satisfy UI needs. This becomes impossible when the UI team have different versions of design. So the UI team must have their own way to present the data and the solution is Converters.
Hope this helps someone.

I'll add my 2 cents to this discussion.
I do use converters, where it makes sense.
Explanation:
There are cases where you need to represent 1 value in Model in more ways in the UI. I expose this value through 1 type. The other is type is handled through converter. If you were to expose 1 value through 2 properties in VM, you would need to manually handle update notifications.
For example I have a model with 2 ints: TotalCount, DoneCount. Now I want both this values to be displayed in TextBlocks and additionally I want to display done percentage.
I solve this using DivisionConverter multi converter which takes 2 previously mentioned ints.
If I were to have special PercentDone in VM, I would need to update this property whenever DoneCount is updated.

Related

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.

MVVM: does change notification muddy the separation between model and viewmodel?

Let's say I have a model which exposes a collection of objects which I will display and change in a GUI.
So we have Model exposing a collection of ModelItem.
The View binds to a ViewModel which exposes an ObservableCollection of ViewModelItem. ViewModelItem is the Viewmodel of ModelItem
The View contains a ListBox and a DataTemplate. the DataTemplate is for items of type ViewModelItem. The View DataContext points at an instance of ViewModel. The ListBox binds to the ObservableCollection.
I control all the code.
So far so simple. Question:
Is it acceptable to expose the collection on the Model as an ObservableCollection? Further, is it acceptable to implement INotifyPropertyChanged on Model and ModelItem?
My concern is I'm muddying the separation between model and viewmodel, but then common sense says, here's a mechanism for notifying changes to elements in my model, lets use it...
Just wanted to get some perspective from others.
Thanks
Short answer:
YES. Use your notification interfaces on your model when you need to notify of changes. Do not worry about muddying your code with this. Be pragmatic.
Long answer:
My philosophy goes like this: When implementing MVVM, bind directly to model objects when there is nothing extra to do. When you need something new (new behavior, properties the view will utilize, etc) then you wrap the model objects in ViewModel objects. A ViewModel that does nothing but delegate data from the model is nothing but extra code. The moment you need to do something to that data past what the model object gives you, you introduce the layer.
So, to extend my thoughts further on that, (and to answer your question more directly), there needs to be a way for the model to tell the ViewModel when something changes. Often, model data is immutable so it doesn't need this notification mechanism, so it isn't necessary. BUT, it is also often the case that the model DOES change. When that happens, the model has two options: use a custom notification method (events, delegates, etc) or use INotifyPropertyChanged.
If you look at the namespace for INotifyPropertyChanged, it is in System.ComponentModel -- not the view -- so I prefer to use it in the model. It is a well-known interface and you can use it to bind directly to your model from your view. No need to implement anything different.
Taking this philosophy one step further, ObservableCollection is in System.Collections.ObjectModel -- also not view-specific -- and it implements System.Collections.Specialized.INotifyCollectionChanged which also is not view-specific. In other words, ObservableCollection was designed to be a collection that notifies its observers of changes. If you have a model that needs to do that, then ObservableCollection is your tool. It just happens to be convenient (not by accident, though) that WPF and Silverlight use these interfaces for data binding.
I guess this is a long-winded way of saying: "YES. Use your notification interfaces on your model when you need to notify of changes. Do not worry about muddying your code with this. Be pragmatic."
It is definitely acceptable to do both. I would even say it's required to do both. Your common sense abilities work just fine. :)
I would only add that if you don't need all the MVVM functionality for your ModelItems, then you can cut some corners by exposing an ObservableCollection<ModelItem> instead of an ObservableCollection<ViewModelItem>, and modifying your DataTemplate to suit. This will save you quite a bit of "preparation" code, so weigh the pros and cons.
It's certainly acceptable to use change notification in the data model if the data model needs change notification. It's also questionable to use change notification in the data model just because the UI needs change notification.
Generally, I design the data model as if there were no UI, and use the view model as an abstraction layer that hides the data model's implementation details from the UI. On the other hand, in a dynamic application it can be the case that the need for change notification is pervasive enough that it just makes more sense to put it in the data model.
No. It's horrible. Your model should not know how it is used. Giving it this knowledge defeats the object of MVVM.
The model should never know it is being used by WPF, winforms, a dos console, as a service or as a lib. If you tell it this, you are going wrong.
It should also be framework independent, not minding if it's part of MVVM, MVC or MXXX!

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?

MVVM WPF ViewModels for Adding New Entity

My concept for MVVM in WPF is that we have a ViewModel for every Model in your application. This means that if we have Customer class (entity) then we will have CustomerViewModel. The CustomerViewModel will have all the properties which are necessary to represent a customer. The CustomerView usercontrol will be responsible for creating the UI for the Customer model.
Now, let's say that we are adding a new customer. So, we have a form which consists of FirstName, LastName etc. Do we need a ViewModel for this scenario. I mean all I have to do is to take all the input values from TextBox and create a Customer object and then save it to the database. Why should I bother creating a ViewModel for this scenario?
First of all, that is not the main purpose of MVVM, to "mirror" everything. The View should provide the means for a user input, and certainly not process calls to any of the database layers. The ViewModel should be a GUI-agnostic application backbone, and it definetly should handle the creating of customers.
That said, what you should do, is have a ViewModel which represents a workspace for handling customers, and not just a customer ViewModel. If you really want to save on a few objects being created, add to that workspace the possibility to create and add a new customer (not CustomerViewModel). That way, you can have a View of the workspace which has elements for each relevant/required property of the customer, and by invoking some command added to that workspace ViewModel, you could get the current values filled in those (data bound to ViewModel) View elements directly to the customer model.
Consider if you could probably drop the specific customer (and other Model) ViewModels if you refactor things a bit, it would be good practice to keep things from adhering blindly to a certain pattern without explicit cause.
Let's pretend for a second that there is no business model. The only thing you have is a view. If you were to model just that view, without any knowledge of what the data means elsewhere in the system, that is a ViewModel.
The goal of a ViewModel is to, well, model the view it backs. This is a different goal than modeling the idea of a customer in your business domain. To say you will have have one ViewModel per business entity, then, is to say you will have one view per business entity, which leads to run-of-the-mill data-focused UI.
In your particular case, think about the customer edit view. It has fields that correspond to a customer's properties, and thus seems like a natural fit for binding to a customer directly. However, where on the customer object is the "Submit" action modeled? Where is the "Cancel" action modeled? Where is it modeled that field X is an enumerated value selected from a list?
How about the password? If persisted as a binary hashed value, does the view know how to hash its text? What if the system has password strength requirements?
The ViewModel is the mortar between the business model and the UI. It takes concerns from one and translates them into terms of the other. It is the point at which all the above issues are addressed. To say a ViewModel isn't necessary is to ignore its necessity.
You don't need to have a separate ViewModel for Add, you only need a single ViewModel which should do Edit and Add scenarios. If you can delete the record from the edit page than that ViewModel should also have the ability to delete. Your ViewModel should reflect the functionality your View exposes regardless of data.
I think you should reconsider having a single ViewModel for each model. I like to think of ViewModels as normalizing behavior inserted of data. By having a ViewModel for each Model class you will run into architecture issues sooner or later. I look at the application from top down overview, what is my UI trying to accomplish and from there I will get to the ViewModel and eventually I will get to my DataFactory and how the ViewModel maps down to data is almost always not 1 to 1 except for the most simplistic Views. If you try to map 1 to 1 you will have bad UI or your data will not be normalized very well.
The Stack we have here is:
View
ViewModel (Controls everything the user can do in the view, wraps properties from our POCO's)
DataFactory (Maps our POCO's to Entity Framework objects and CRUD)
POCO's (Business Logic, all rules and validation)
Entity Framework (Model, Data Access)
One note here is that ViewModel contains properties from multiple POCO's!
We inject the DataFactory through StructureMap and Unit test with xUnit along with Moq.
To answer you second question I would create a separate view only view to drop in as a user control. But you should still have a CRUD ViewModel in you app that encapsulate all that functionality in a user friendly way.
Thanks.
One reason for this VM abstraction is for testability. Another reason why you want a ViewModel is because it's basically a Data Transfer Object that might be a combination of fields from multiple models in a single container that is more relevant to your current view. Yet another reason to have VM is to take advantage of WPF two ways binding capabilities.
Using your regular model (plain POCO), you can update the View when your model change, but since your model does not implement dependency properties (most likely), you won't be able to take advantage of updating your model when the value in WPF control changes. Which mean you have to manual add a handler and do the copy this value from this control back to the model kind of thing.

How do I maintain coherency between model and view-model in MVVM pattern?

Problem Statement
I'm writing a very basic WPF application to alter the contents of a configuration file. The data format is an XML file with a schema. I want to use it as a learning project for MVVM, so I have duly divided the code into
Model: C# classes auto-generated from xsd.exe
View-Model: View-friendly representation of the Model.
View: Xaml and empty code behind
I understand how the View-Model can make View-binding a breeze. However, doesn't that leave the View-Model <-> Model semantics very awkward? Xsd.exe generates C# classes with arrays for multiple XML elements. However, at the V-VM level you need Observable Collections.
Questions:
Does this really mean I have to keep two completely different collection types representing the same data in coherence?
What are the best practices for maintaining coherence between the Model and the View-Model?
I'm not a big expert, but I think that is the case yes. The general idea is indeed to propagate change between the view and the viewModel via Binding, and then between the ViewModel and the Model via events (in the Model -> ViewModel direction) or dependency (in the other direction).
I don't know how standard that is, but my understanding of MVVM is that the ViewModel should hold a reference to the model so that when the user modifies the view, the ViewModel should call the appropriate code on the model. The other way round, the Model should raise events when modified, and the ViewModel should update itself accordingly (the ViewModel being an observer to the model).
#Does this really mean I have to keep two completely different collection types representing the same data in coherence?
I think yes. It's pretty boring, but it works quite well. Hopefully, in the future we will have also a code generator to create the ViewModel part.
Karl is working on that: http://karlshifflett.wordpress.com/mvvm/
You need clearly ObservableCollections at the viewmodel so, yes, you will need two
completely different collection types in the model and in the viewmodel.
I have done an article about doing undo / redo in MVVM where you can find a possible solution to this. It uses what I call the MirrorCollection: an ObservableCollection derived class witch automatically obtains his items from a List (the list of the model).
I think it is an interesting solution, you can find the articles here
Part 1: Using the Viewmodel pattern to provide Undo / Redo in WPF
Part 2: Viewmodelling lists (here is the MirrorCollection definition)
Expose Events or delegates in Model and hook to the same in ViewModel, when ever values in the model changes notify to viewmodel via event or delegates and from Viewmodle you can update the UI.
If you want to update it from view model to model as simple as that just call some method pass the new values

Resources