views:

44

answers:

2

I'm completely new to M-V-VM and very new to Silverlight, just reading about it for the first time today. As a sample, I am creating a model containing a list of items. My (Silverlight 4) View contains a listbox and my ViewModel will look to the model to retrieve the collection that the listbox will bind to.

My question is this. I think it would be good to use an ObservableCollection to hold the items that the listbox binds to. This would be an ObseravleCollection in the ViewModel. Should I also use this type of collection in the model, or should I use another collection type and do smoe conversion between model and viewmodel?

A: 

Hi there,

the usual way of doing this is to use IList/List or something similar in the model and then do a conversion in the ViewModel. So in the model you will have something like IList and in the ViewModel you convert it to ObservableCollection (usually in the ViewModel's constructor).

Cheers, Alex

alexander.biskop
Thanks. How would you normally deal with updates coming back. Trap and add to the model from the ViewModel?
Bill Jeeves
Hi, yes, if you need to know about items being added/removed to/from your ObservableCollection (e.g. through user interaction) and need to propagate those changes into the model, you can handle the CollectionChanged event provided by ObservableCollection to do so.
alexander.biskop
A: 

There are 3 basic scenarios (in order of increasing complexity):

  1. model simply provides an access to a backend services and does no caching of data flowing through it at all
  2. model exposes a collection of items, vms don't have their own collections, and then views are simply bound to collection in model object
  3. model exposes a data source, vms have their own collection that serve as window into this data source, and views are bound to collections in vms.

In first case you'd use List to simply pass a requested data to vms, in other cases you'd use ObservableCollection so that either views will be properly updated via binding (case #2) or vms can properly update its own collections (case #3)

PL