How do I structure MVVM with Collections?

后端 未结 4 488
不知归路
不知归路 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条回答
  •  春和景丽
    2021-02-01 18:20

    In my experience, the only time you get away with exposing model objects to the view is if you're doing simple read-only presentation, e.g. displaying a string property in a ComboBox. If there's any kind of actual UI involving the object (especially one involving two-way data binding), a view model is needed.

    Typically, a master VM's constructor will look like this:

    public MasterViewModel(MasterModel m)
    {
       _Model = m;
       _Detail = new ObservableCollection(m.Detail);
    }
    

    where MasterModel.Detail is a collection of DetailModel objects, and _Detail is a backing field for a Detail property that's exposed to the view.

    As far as adding, removing, and reordering items in this list is concerned, in the UI at least this will be done through commands on the MasterViewModel, which must manipulate both MasterModel.Detail and MasterViewModel.Detail. That's a bit of a pain, but unless you want to repopulate MasterViewModel.Detail after every change to MasterModel.Detail, it's really unavoidable.

    On the other hand, if you've been wondering "why would I ever need to write unit tests for view models?", now you know.

提交回复
热议问题