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.
Related
I've to start a fresh application and I'm currently asking myself if there is some kind of best-pratice on how to bind our model to the view through the ViewModel.
Currently, I see two options:
My ViewModel duplicates every field that has to be bound to the View
My ViewModel expose a Model object instance, on which the different properties of the ViewModel bounds.
What I can see:
Duplicating the Model properties in the ViewModel
Advantages:
I keep a clear separation of concern between View and Model
I can implement here all the validation mechanism
Disadvantages:
It makes a LOT of code to duplicate(we create a new client for an existing solution, we have currently more than 1000 models)
More code to write = more to maintain = more errors
Exposing the Model properties in the ViewModel
Advantages:
The ViewModel will more focus on how to retrieve and save models
ViewModels are cleaner to read
This takes much less time to implement
Disadvantages:
Not sure that the model is the best place for the data validation
So, any guidance you could provide me, or way of having both of the two world would be greatly appreciated.
I wouldn't duplicate the values required in the view model, but it does depend on how the model looks and how you want the view to look. Create properties on the view model that wrap the model properties.
#j4n try to implement MODEL with INotifyPropertyChanged and try to wrap continents of Model in class so you can use observablecollection in it . Use of observablecollection reduce duplicate property
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.
I have multiple of views (user controls), each with its own ViewModel. To navigate between them I am using buttons. Buttons display image and text from corresponding view model and also need column and row (because there are like 10 views: 10 columns with different number of rows each).
Right now buttons are created dynamically (I made a Navigator control for this) and for view models I have base class to hold text, image, column and row. Number of views available will be different (depends on user level and certain settings), that's why it's I need control here.
Question: how shall my control get data from view models?
Right now I have interface INavigator, defined in (lol) control itself. And view models implement it. I could go opposite, let my control to know about view models. Both looks wrong.
There is a single Navigator control what has, lets say, Items bound to a list of view models. It can cast each view model to INavigator or ViewModelBase (common for all pages) to obtain specific view model image, text, column and row. So either view model knows about control (to implement INavigator) or control knows about ViewModelBase.. And this is a problem, both solution bind tight control and view models, which is bad in mvvm.
Schematically
The way you've drawn your diagram answers your own question as to how you should structure the code for this.
What you need is one VM (let's call it MainVM) which contains an ObservableCollection<VMBase> of the other VMs (using your base type so that they can all happily live in the same collection).
Your View needs an ItemsControl (bound to your ObservableCollection<VMBase>) where you specify a DataTemplate for the Button using the properties exposed by the VMBase type only. Set the Command property in the Button to call SwitchCommand, CommandParameter is set to the item itself (i.e. {Binding .}).
Your View also needs a ContentControl bound to a SelectedVM property on MainVM which you can populate.
Implement SwitchCommand to set the SelectedVM property based on the value from the CommandParameter.
public void ExecuteSwitchCommand(object parameter)
{
var vmBase = parameter as VMBase;
if (vmBase != null)
SelectedVM = vmBase;
}
All properties mentioned here should be INotifyPropertyChanged enabled so that the View registers when they change and updates the UI.
To get the different UIs for the ContentControl, add type-specific DataTemplates for each of your specific VM types to the Resources file of your View (or if you're smart and are building a custom plug-in framework, merge the Resource Dictionaries).
A lot of people forget with MVVM that the whole point is that there is a purposeful separation of View from ViewModel, thus meaning you can potentially have many Views for a single ViewModel, which is what this demonstrates.
I find it's easiest to think of MVVM as a top-down approach... View knows about it's ViewModel, ViewModel knows about its Model, but Model does not know about its ViewModel and ViewModel does not know about its View.
I also find a View-first approach to development the easiest to work with, as UI development in XAML is static (has to be).
I think a lot of people get to wrapped up in 'making every component (M, V, VM) standalone and replaceable', myself included, but I've slowly come to the conclusion that is just counter-productive.
Technically, sure you could get very complicated and using IoC containers, create some ViewLocator object which binds a View-type to a ViewModel-type, but... what exactly does that gain you besides more confusion? It makes it honestly harder (because I've done this at one point) to develop because now you've lost design-time support first and foremost, among other things; and you're still either binding to a specific view model interface in your view or creating the binding at run-time. Why complicate it?
This article is a good read, and the first Note: explicitly talks about View vs. ViewModel. Hopefully, it will help you draw your own conclusions.
To directly answer your question, I think having your ViewModels implement an INavigator interface of some sort is probably ideal. Remember your VM is 'glue' between your view and model/business logic, its job is to transform business data into data that is consumable by your views, so it exists somewhere between both your UI and business layers.
This is why there are things like Messengers and View Services, which is where your navigator service on the ViewModels can fit in nicely.
I think the design has led to a no way out situation.
I believe that creating a custom button control where the dependency properties tie the image, the row and column actually provide a way for the page, which it resides on ,to get that information to them; whether they are dynamically created or not.
Continuing on with that thought. There is no MVVM logic applied to a custom control, the control contains what it needs to do its job and that is through the dependency properties as mentioned. Any functionality of the button should be done by commanding; all this makes the button data driven and robust enough to use in a MVVM methodology or not.
Question: how shall my control get data from view models?
There should only one viewmodel which is the page the control resides on. The control is simply bound to information which ultimately resides on that VM. How it gets there, that is up to the programmer. If the button is going to contain state data, that is bound from its dependency property in a two way fashion back to the item it is bound to.
By keeping VMs out of the buttons and only having one VM that is the best way to segregate and maintain the data. Unless I am really missing something here....
Same as others here I find it a bit hard to actually understand what you are asking, so this is quite general. The answer to the question header is simply: the Control gets the data from the ViewModel through bindings, always. You set the DataContext of your Control to the corresponding ViewModel, and from there you keep the ViewModel and the Control synchronized:
If you add an ItemsControl containing buttons to the View, you add an ObservableCollection<ButtonViewModel> to the ViewModel and bind the ItemsSource of the ItemsControl to this.
If you allow the user to dynamically add content to the View, the actual code that does it resides in the ViewModel, e.g. when the user clicks on a button "Add Button", you use the Command property to call a ViewModel method that adds a ButtonViewModel to the collection and the View will automatically reflect your changes.
There do exist complicated cases that are impossible to code exclusively in the ViewModel, I have found Behaviors to be the missing link there, but I'll get into that when you show me the specific case.
If you'd like to get a working example, please provide as much code as you can, with your exact expectations of what it should do.
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.
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)