How do I structure MVVM with Collections?

后端 未结 4 487
不知归路
不知归路 2021-02-01 17:45

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

4条回答
  •  猫巷女王i
    2021-02-01 18:01

    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

提交回复
热议问题