Should my ViewModel have an ObservableCollection of Views or ViewModels?

前端 未结 3 1416
无人共我
无人共我 2021-02-04 11:22

I\'m trying to understand the basic MVVM design approach when using ItemsControl by binding it via DataTemplates to ObservableCollectio

相关标签:
3条回答
  • 2021-02-04 12:05

    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.

    0 讨论(0)
  • 2021-02-04 12:19

    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?

    0 讨论(0)
  • 2021-02-04 12:21

    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).
    0 讨论(0)
提交回复
热议问题