Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should my ViewModel have an ObservableCollection of Views or ViewModels?

I'm trying to understand the basic MVVM design approach when using ItemsControl by binding it via DataTemplates to ObservableCollections on the ViewModel.

I've seen examples that bind to ObservableCollections of strings, Views, and ViewModels.

Binding to strings seems to be only for demos, it is the binding to "ViewModels that contain collections of Views that contain collections of ViewModels" that the power of WPF seems to really come out.

For those of use proficient in the MVVM pattern, what is your standard approach to binding ItemsControl, ListView, ListBox to collections in a ViewModel? I'm looking for advice from experience like this:

  • always use ObservableCollection<...> and never List<...> because...
  • something better than ItemsControl to display a collection is...
  • in order to get filtering to work in your ViewModel instead of code-behind, use...
  • use collections of Views when ... and collections of ViewModels when...
  • 90% of the time I create an ItemsControl and bind it to an ObservableCollection of Views which have their own ViewModels...
like image 939
Edward Tanguay Avatar asked Jun 08 '09 12:06

Edward Tanguay


3 Answers

I would use an ObservableCollection of ViewModels for the following reasons:

  • ObservableCollection already has events available for signaling when it has been modified (e.g. when items are added/removed from the collection).
  • We're at the ViewModel 'layer' so it provides cleaner separation to have a ViewModel contain a collection of ViewModels rather than Views
  • If it is necessary to modify or get data from items within the collection you can more easily modify/access that data if the items are ViewModels (if they're views you'll frequently be casting the View's DataContext or accessing its UI elements).
like image 196
Richard McGuire Avatar answered Sep 18 '22 02:09

Richard McGuire


I like using an ObservableCollection of ViewModels. The view that binds to the collection can define a DataTemplate that gives the ViewModel its look. This leads to less coupling among the components.

like image 25
denis phillips Avatar answered Sep 20 '22 02:09

denis phillips


I have the same question, but replace the "view" with "model". :)

I have a MODEL with a collection of other models. I want my viewmodel to have an observable collection of other viewmodels, but once I instantiate it like that - the connection between the model collection content is lost. Do I now need to start wiring all the events from the viewmodels observable collection back to the models collection?

like image 32
Arielr Avatar answered Sep 21 '22 02:09

Arielr