tags:

views:

864

answers:

3

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?

+4  A: 

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).

Axelle Ziegler
+2  A: 

@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/

marco.ragogna
+2  A: 

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)

DaniCE