MVVM and where to keep displayed fields/properties - c#

I am learning MVVM by building a simple WPF calculator app.
In this simple app, there is one view (Main window), one ViewModel, and one Model (the calculation engine).
My calculator displays the current value of all previous operations, and the operations that got to that value.
For example a display might look like this:
1 * 2 * 3
6
I am wondering if these should be saved as Properties on the ViewModel, Model, or both?
More general -- should the ViewModel contain only properties that exist on the Model, or this is not mandatory?
In this case i would save a CurrentValue and DisplayValue properties, just wondering which architecture layer should these belong to.

In MVVM, ViewModels allow you to shape multiple entities from one or more data models or sources into a single object, optimized for consumption and rendering by the view. The below image illustrates the concept of a ViewModel:
The purpose of a ViewModel is for the view to have a single object to render, alleviating the need for UI logic code in the view that would otherwise be necessary. This means the only responsibility, or concern, of the view is to render that single ViewModel object, aiding in a cleaner separation of concerns (SoC). Concerns are distinct aspects of the application that have a particular purpose (i.e., concern), and keeping these aspects apart means your application is more organized, and the code more focused. Putting data manipulation code in its own location away from the view and controller, enforces SoC.
Using ViewModels in MVNM for finer granularity and better SoC leads to more easily maintainable and testable code. Remember, unit testing is about testing small units.

I am wondering if these should be saved as Properties on the ViewModel, Model, or both?
In my opinion these should be property in ViewModel. Why these should be in the Model too? There is no benefit I can think of having this in Model too. These properties will only make sense to user in View so they should be displayed via ViewModel in the View. Model has nothing to do with it. At most you will have to pass expression 1 * 2 * 3 to Model and get results back, as you mentioned your engine is in Model.
More general -- should the ViewModel contain only properties that exist on the Model, or this is not mandatory?
In general, a ViewModel should contain all the properties that have to be displayed in the View (via ViewModel). Regardless of the fact whether this property exists in Model or not. There is no rule that if this exists in ViwModel it should must be in Model too and vice versa. Generally Model is nothing more than representation of your business entities.

First of all, the model is not the place, where all your logic should be. The model is just the data for the view.
View model should contain any code needed to correctly adapt the model data to WPF display.
In your case you should work on an architecture a bit more.
There should be a class like CalculatorProcessor. View model may have properties for CurrentExpression, that, when a button = is pressed, are passed to a CalculatorProcessor to get processed (calculated) in sequece.
A result is also a property on a view model class that a view's controls are bound to.

ViewModel is specifically created for databinding purposes and as you expected contains properties needed by the view. In my opinion if you need any computed values to be displayed in the view, you can expose them as properties on view model.

A model class is not only a business object, even if the model classes typically provide property and collection change notification events through change notification interfaces, so they can be data bound in the view, you can define an observable collection of instances of a class representing operations that represent he Ui interaction, so when a new op is inserted by the user, you add it to the collection and the UI will automatically reflect it through the binding to an templated listbox (for example)

Related

Should I have an encapsulating ViewModel for each Model?

I've been working with WPF and MVVM a lot lately. I was under the impression that I understood the MVVM pattern quite well but I've begun having some doubts.
Right now, I have an encapsulating ViewModel object for each Model object.
Let's say my Model contains two classes: Property, which contains a list of PropertyValue. In my ViewModel, I have a PropertyVm, which contains a Property and a list of PropertyValueVm (each containing a PropertyValue). Both Vm's implement a BaseVm which contains the OnPropertyChanged method.
Consider a View with two comboboxes, for Property and PropertyValue. The first combobox's ItemsSource will be bound to a collection of PropertyVms and the second combobox's ItemsSource will be bound to the PropertyValueVms of the PropertyVm selected in combobox 1.
This is all based on the article that got me to explore WPF and MVVM in the first place: Simplifying the WPF TreeView by Using the ViewModel Pattern, by Josh Smith
However, I'm becoming increasingly annoyed with the large amount of ViewModel classes my project contains, some of which contain very little code or simply nothing but the corresponding Model class.
Other implementations I've come across have the INotifyPropertyChanged on the Model objects instead. This would mean you'd assign the Model objects to the Comboboxes directly. This would slim down the amount of ViewModel classes, but doesn't this violate the basics of MVVM?
I've also seen people advocating a single ViewModel per View. But I fear this would turn my ViewModel classes into humongous, incoherent walls of texts.
So my question in short: Should I have an encapsulating ViewModel for each Model? If not, then what is best practice?
The primary driver of MVVM is to maximise the testable code via the strong separation of presentation and presentation logic. Ideally we encapsulate the presentation logic in one or more view models - so in terms of your sub-question, have as many view models as makes sense. Dividing the functionality up into a series of smaller view models is good practice from my experience. But there is no one-size-fits-all way to implement this. So in some ways, the answer to the question is: it depends on your situation.
If your model never changes then you've reached a religious fork in the road. The pragmatist exposes the model to UI binding (guilty!!). The purist wraps the model in a view model because the VM sits between M and V in the design and if we don't dogmatically adhere to this then bad things must surely happen.
If your model changes then you have design choices. You can keep the model immutable and refresh your view model with a new version of the model and raise changes from there. Or, if your architecture facilitates an ever updating model that the UI just needs to represent then ask yourself if you truly gain by sticking a view model in the middle. But!! As soon as you get a sniff of logic creeping into the model then it's worth a view model.

Creating object of view class in ViewModel class in mvvm

I am working on mvvm in c# wpf, I have a little understanding of mvvm.
I am creating an object of my View class in My ViewMode classl.so is it violating mvvm pattern? and how ? it would be great if some one explains this in detail..
The whole point of the MVVM pattern is to maintain separation of the View (the display that presents controls to the user) from the Model (data, the business logic, data-access) and the ViewModel (the glue between the model and the view). The VM should not have to worry about UI (i.e. View) concerns, so creating and using a view within a viewmodel is violating that MVVM pattern.
A View is nearly always made up of UI elements, such as buttons or textblocks. A Viewmodel should be concerned with things like properties, such as a UserName, or a StartDate, or a WarningState. These VM properties are then bound (with DataBinding) to properties on UI elements within a view ... so the view has a dependency on the VM but not the other way around. Where the VM gets the data from to populate those properties in the first place is the model, or for data-entry maybe they'll all be blank to begin with and the application relies on the user entering data in the view.
You might want to bind the WarningState to a TextBox, for example, but equally you could bind it to a ComboBox. Or you could use a converter and bind it to the foreground colour of a rectangle, or the background colour of a UI element that is used for something else entirely different.
The point is that these are things the VM doesn't need to worry about: all it cares about is presenting data/state. It is up to the view how it deals with that information (or doesn't deal with it). In this way you could completely replace the view with a different version, and not have to change anything in your VM ... you have successfully separated your display from your logic.

Should the view model match closer to view or model?

Let's say we have a view which has a view model as data context. It is binded to a property called Visible.
What type should the property be ?
Boolean (more model friendly, but forces the use of a converter) ?
Visibility (more view friendly) ?
Leave the bool value in the ViewModel and use a BoolToVisibilityConverter in the View.
Reason:
ViewModel should be View-agnostic, and UI-Framework-agnostic. That is, you should be able to copy your ViewModel into a console application and hit F5.
Make sure you leverage MarkupExtension to simplify converter usage
To the title question, in general: Closer to the View.
To the example: Use a boolean.
Your VM should be the logical model of the View. But it should not contain any GUI related types (Visibility).
I think of the view model as being the representative of the application workflow. In general a given application should have a view model per view - but that doesn't mean that the view model should in any way be coupled with a specific view - I think of it as the view model matches up with a theoretical view at some point in the application's workflow.
View models should ABSOLUTELY NOT expose UI-specific types (i.e. Visibility, Image etc.). Keep your view model UI Agnostic and use value converters to convert general types to UI Specific ones.
It should NOT be representative of the model unless the model happens to be closely represented by the view you are looking at.
You should go for Boolean. It is also more flexible, i.e. if you want to bind this property to Checkbox you could easily do this without requiring to change any ViewModel Code and gives your UI guy more freedom to decide how the value should be bound in the UI.

How to get changes from the model into the modelview?

I'm currently busy with rewriting an application into MVVM (in stages, because it is a lot of work).
Currently I can fill listviews and controls depending on changes in the model view and also listview selections are coupled correctly (at least I know how I can do it correctly).
However, I was wondering about changes in the model to be reflected in the modelview (and thus in the view). Should I add INotifyPropertyChange interfaces on all items in the model and subscribe on the modelview (maybe even like a chain if I want to subscribe to an item that is not in the 'top' of the model hierarchy)?
E.g. I have a list A containing a list B etc. Do I need to subscribe in list A for property changes of list B and in the model view subscribe to list A? And unsubscribe if another list selection is made (resulting in a lot of unsubscribe and new subscribe items)?
Thanks for reading/answering.
Yes, typically you would implement INotifyPropertyChanged on your models, and subscribe in your view models. If you are using a framework such as CSLA for your business entities, then Rocky describes an anemic vs rich model, where in the later you expose the model directly to the view on your view model as a property.
I think INotifyPropertyChanged is a stable dependency, so it doesn't pollute your models significantly. Some people do not like exposing the model directly to the view, but I find it saves a lot or repeat code. You may find that if you don't, your view models end up duplicating many of the properties on your model, without adding any value.
If I understand right, you want to programmatically change your data in the model and show the updated data via the viewmodel accordingly?
I would suggest you change the viewmodel properties in your code instead and only use the models for loading/saving the data, that would eliminate that problem.

MVVM pattern in wpf - one data model , multiple view models

I am currently designing simple editor as part of learning process. Its basicaly hierarchical tree structure of polygons-lines-points, that is implemented in data model. I need to display these data in two views
First view: hierarchical data in tree view item
Second view: rendered geometry on screen
Following the MVVM pattern i have implemented model view classes around data model ( point model view, line model view, etc.. ) . In tree view I am using hierarchical data templates to properly display specific data. On second view I need to render current state of geometry, currently its just one model-view wrapper around polygon data class, that travels all children and render them in onRender method. In this case I am using multiple view models over the same data, both for quite different purpose.
There is a problem when I make some modification in tree view model (adding points for example) , resulting in change of underlying data model. However second view model does not directly observe data in model view, it updates render view only if I make modification trough its modelview clas. Is there some elegant solution to update both view models concurently ?
I solved this by introducing a Presenter. Here's basically how it works:
My domain model contains some representation of a process (call it a task, workflow, or whatever). It contains the "business logic" for the actual actions you're doing.
My presenter is told to display the process.
It instantiates the ViewModel (and, if necessary, multiple ViewModels) giving each ViewModel a reference to the presenter (a callback).
After instantiating and displaying the ViewModels, it passes them a reference to the Model and tells them to update their state from it.
ViewModels don't maintain a direct reference to the Model. When they want to take an action, they use the callback to the Presenter that was provided to them when instantiated. The Presenter actually executes the action against the Model (process, task, whatever).
After executing the action, the Presenter again passes a reference to the newly updated Model to all of the ViewModels, instructing them to refresh their state.
That keeps them all in sync without any ViewModel having to know about any other ViewModels. All of my Hierarchical ViewModels implement an interface IViewModelWithChildren, which exposes an IEnumerable<IViewModel> property, which lets the Presenter walk any given ViewModel tree and notify all of them, as long as it has a reference to the root ViewModel.
I also like it because it funnels all user actions through a single point (the Presenter callback) and I can inject certain concerns there. For instance, if an unhandled exception happens in the Model logic, I can catch it at that point and instantiate a nice MessageViewModel to display to the user.
If you must use different viewmodels for the two views, you can have the viewmodel for the geometry view subscribe to PropertyChanged on the hierarchical viewmodel, or you can expose a different event for this. That way, the geometry view model will know to look again at the underlying model and update itself.
If you want it further decoupled, you can use an event aggregator, as available in the Prism project.

Categories