ViewModel tree vs. frequently updating Model tree - wpf

In my WPF MVVM application my model is a complex tree of Model objects wich constantly changes at runtime. Model instances come and go at runtime, change their position within the tree and of course change their many properties. My View is almost a one-to-one visual representation of that tree. Every Model instance is in 80% of the cases also a node in the tree.
My question is now how I would design the ViewModel around this? My problem is that there are quite a lot of different Model types with each quite a lot of properties. If I understood MVVM corretcly the view should not communicate with the Model directly so this would mean that I would have to create a ViewModel type for each Model type and have to rewrap each property of the Model type in the ViewModel.
Also the ViewModel would need to "bind" to the propertychanges of the Model to pass it along to the view (using wpf datatbinding). I would need some factory that creates and introduces a ViewModel instance for each Model that appears anew and I would habe to dispose each ViewModel instance when the corresponding Model disappears. I end up keeping track of all instances I created. It is unbelievable how much bloat code is generated dues to this double wrapping.
Is this really a good approach? Each entity and each property more ore less exists twice and I have a lot of extra code keeping Model and View in sync. How do you handle this? Is there a more clever way to solve this?
Does anyone have a reference/sample implementation for this that does it better than I do?

I think you may run into trap of paradigm if you follow this path. MVVM is nothing more than a pattern, which simplifies development in WPF world. If it doesn't - don't use it or revise your approach. I wouldn't spend 80% of my time just to check the "Using MVVM" field.
Now back to your question. Correct me if I'm wrong, but it sounds like you are looking at MVVM from opposite direction: you don't need Model to ViewModel one-to-one correspondence. Usually you create ViewModels based on your View first, and only then on a Model.
Generally you look on a screen mockup from graphic designers, and create corresponding ViewModel, which takes all necessary fields from the Model, wraps/modify/format/combine them to make View development as easy as possible.
You said that your View is almost one-to-one visual representation of the Model. In this case it may have sense to create a very simple ViewModel which exposes root object of your model-tree, and let View consume model directly via that property. Then if you need some View customizations or commands processing you can delegate that to ViewModel.
Sorry for very vague answer. Maybe if you ask more specific question we could dispel the confusion :)...

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.

MVVM: Decouple Model from ViewModel

I've just started learning WPF MVVM using Prism and Unity.
Decoupling the view from the viewmodel works pretty well, but I don't get how wire up my viewmodel and my model.
I doesn't feel right to just create a new EntityObject right in my viewmodel. I have already skim-read the WAF BookLibrary sample but it is quite bulky and adds a lot of extra stuff around the essential part (binding between view and viewmodel), and the Prism docs don't say a word (as far as I read it) about viewmodel - model interaction.
Does anyone know a good source that explains how to use viewmodel and model in a clean way or can me give some advise?
Best Regards
Jay
Everyone will have their own opinions on this. Personally I don't mind using the model directly in the view model. For me, the whole idea of a view model is to extend your model in such a way that it can be consumed by a view.
A simple example of this would be person object, It would have model properties like like name and age for instance. When I get to the view model stage I may add properties to it like visibility which would not make sense on the model proper.
Another point to note is I would consider a model to be the data and the view model to be the context. So you may have a "Card" View Model for a person but you may also have a "List Item" view model that represents the same model in a different context, with different view model specific properties.
I do tend to make my models up using interfaces where relevant and use Inversion of control to inject them into the view model, that way the only thing my view model actually knows is that it needs an IPerson and that it will be provided in the constructor.
As I said other people will have different ideas, all are correct and its up to you to work out which one suits your needs.

View - ViewModel - Entity Framework 4

I'm looking for a simple way to link a view to a viewmodel and then to Entity Framework through databinding.
Can someout out there give me some pointers. What I'm looking for is a very simple implementation that would allow the view to automatically list all the contents of for example a one field table and for changes in the view to be propogated back to the database through EF.
AAfter spending a long time looking I'm still searching for a way to do this and any help would be very much appreciated.
Thanks,
Technically using a ViewModel means you don't actually bind to your entities. Your ViewModel classes should have everything on them that is needed by the view (and yes, this can cause what feels like duplication, but it's for the greater good), and therefore you don't even have this problem.
You can ease the pain of duplication by implementing something like AutoMapper to avoid the legwork of "left to right" coding where you're just copying properties across.
If you are binding a list, consider having an EmployeeListViewModel that has a property of type IList<EmployeeViewModel> on it, so that you're still not binding your entities directly to the view. This is useful because you can then reuse that EmployeeViewModel for a single-record detail view.

Grids with ViewModels - WPF

Sorry if this has already been asked, but I just want to make sure that I'm doing this right.
If I have a domian object that has say 10 properties on it. I have a grid on my main form that I want to show the pretty much all the the properties from the model.
I created a viewmodel to wrap the domain object to show in the gridview but then I have to expose all the properties again. I just feel binding straight against the model through the viewmodel feels dirty and defects the purpose a bit.
So for example I don't really like this:
{Binding DomainObject.Property}
where DomainObject is property on my view model.
So my main question is, should I expose all the properties on the model through the view model just to bind it to the grid?
EDIT: Just for added information the domian objects are LINQ-To-SQL objects, so I don't think they implement INotifyPropertyChanged but I'm not sure.
Some people will say it doesn't matter, others say it does. I'm in the latter camp, for these reasons:
You increase the dependencies of the view, as it now depends on the data model, not just the view model.
You require the designers need to know the properties and structure of your data model.
You create more work for the (almost inevitable) refactoring when you decide you need a layer of indirection for formatting, validation, or whatever it might be.
As Thomas pointed out, data models often don't implement change notification
Yes, it's a little more work, but I believe it's worth it to reduce decoupling, maintenance headaches, collaboration with designers, and correctness.
PS. If you find yourself in this situation a lot, you might consider an implementation of ICustomTypeDescriptor that wraps any data object and exposes its properties with change notification. That way your VM can extend this generic wrapper until you decide you need to pull properties out for purposes such as formatting and validation.
If you need change notification on the properties and the model doesn't implement INotifyPropertyChanged, then you need to create new properties on the ViewModel. Otherwise, it's probably not a big issue to bind directly to the model : the MVVM pattern is just a guideline, you can bend the rules a little if necessary...
I think it is a matter of personal preference. I happen to believe it is perfectly fine to expose the Model in a single object from the ViewModel. Recreating all the properties of the Model in the ViewModel just results in a bunch of extra code.
However, this only works provided your Model implements change notifications so the data binding works.

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