Best practice for child Collections

Mar 23, 2011 at 12:38 PM

Hello everybody. 

I'm having some trouble figuring out how to manage child collections from my Model and ViewModel.

For example, I have this Model (oversimplified of course):

class Person

{

int Id {get; set;}

string Name{ get; set;}

List<Phone> Phones {get; set;}

}

So in my ViewModel I map the simple properties, but what about the Phones collection (that should be a ObservableCollection to expose to the View). How to sync the model collection with the ViewModel one? 

What approach you propose for this scenario?

 

Thanks in advance.

Maximiliano.

Coordinator
Mar 23, 2011 at 12:44 PM

You have several options that you can use:

1) Implement the ObservableCollection in the model as well (is handy if you want to receive notifications that are caused by the model).

2) Use custom mappings between the view model and model. This is how you should do that:

  1. Create custom observable collection on the view model without a mapping
  2. In the Initialize() method of the view-model, copy the items from the Model (Phones) into the custom observable collection
  3. In the Save() method of the view-model, you will have to sync the changes back
  4. In the Cancel() method, discard changes (but you can probably skip this step because you shouldn't modify the model collection in-between states)

As you can see, the latter is much more work, and you need to check the changes and determine whether you want to replace or modify changes in the original model list. However, these are the options you have where option 1 is Catel specific, option 2 works for all MVVM frameworks (at least as long as they support save and cancel methods).

I hope this clears up the options you have. If not, just let us know!