I\'m having trouble understanding how to apply the MVVM pattern when Lists/Collections are involved.
Say the MainModel
has a few properties and methods, as
Usually Models
are nothing more than data objects. They shouldn't contain any code to do things like add/remove items from a list. This is the ViewModel's
job.
In your case, I would create a MainViewModel
that has the following properties:
ObservableCollection Details
ICommand AddDetailCommand
ICommand RemoveDetailCommand
If your MainModel
class is a data object, you can either expose it, or it's properties from the MainViewModel
as well. Exposing it's Properties is the "MVVM purist" approach, while exposing the entire Model is sometimes more practical.
Your MainViewModel
is in charge of creating the initial list of DetailViewModels
, and it is in charge of Adding/Removing these items as well. For example, in the PropertyChanged
event for the MainViewModel.MainModel
property, it might rebuild the MainViewModel.Details
collection, and the CollectionChanged
event for the MainViewModel.Details
property would update MainViewModel.MainModel.Details