MVVM: locating other ViewModels

六眼飞鱼酱① 提交于 2019-12-23 03:41:41

问题


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.



来源:https://stackoverflow.com/questions/1136052/mvvm-locating-other-viewmodels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!