MVVM: locating other ViewModels

2019-05-30 07:40发布

问题:

I have quite a large number of parent-detail ViewModels in my MVVM application. Something like this:

SchoolsViewModel
  +- SchoolViewModel
      +- LessonViewModel
          +- PupilsViewModel
              +- PupilViewModel
          +- TeacherViewModel
      +- PupilsViewModel
          +- PupilViewModel
              +- LessonsViewModel
      +- TeachersViewModel

And so on...

In addition, a single view model can appear in more than one place, depending on whether the user is browsing by lesson or pupil, etc.

How would you allow for sharing of child ViewModels between different parent ViewModels? For example, "Pupil A" will be present in the highest-level PupilsViewModel and also in a number of PupilsViewModels contained within LessonViewModels. Would you create multiple PupilViewModel objects referring to the same data model? Or somehow locate an existing view model for the data model?

This question has another related question: MVVM and StructureMap usage

回答1:

I would suggest having only one instance of Pupil A. That way, when the user updates a pupil in one place, that pupil is updated everywhere else in the application. In order to accomplish this, you need to implement INotifyPropertyChanged on each ViewModel, but this is standard practice in MVVM.

In your case, I suggest using CollectionViews to provide different views of your PupilsViewModel (collection) to different parts of your application. That way they're operating on the same underlying data, but the different parts of the application can navigate over them independently.



回答2:

Why not use DataTemplates for defining which view will bind to each model? And on the views, you can simply use an ContentPresenter bound to the model property of the parent viewmodel.

I think it will do the trick.