简体   繁体   English

WPF和MVVM - 如何在多个视图模型中共享一个模型

[英]WPF & MVVM - How to share one model in multiple viewmodels

I am currently working on developing an application, using WPF and MVVM design pattern. 我目前正在使用WPF和MVVM设计模式开发应用程序。 I am trying to do the following things: 我正在尝试做以下事情:

I would like to have two models, parent and child. 我想有两个模型,父母和孩子。 The parent class has multiple objects of child class, and each child shares one parent object. 父类有多个子类对象,每个子对象共享一个父对象。

Then, I would like to create two view models, parent view model and child view model. 然后,我想创建两个视图模型,父视图模型和子视图模型。 Also I want to let the parent view model have a parent model and allocate child models to each child view model from the parent model. 另外,我想让父视图模型具有父模型,并将子模型分配给父模型中的每个子视图模型。

One solution I could think of was to let the parent view model has the child view models and distribute the child model to each child view model inside the parent view model. 我能想到的一个解决方案是让父视图模型具有子视图模型,并将子模型分发给父视图模型中的每个子视图模型。

However, I don't want to let the parent view model have the child view models because the relationship of parent and child is already created in models. 但是,我不想让父视图模型具有子视图模型,因为已经在模型中创建了父视图和子视图的关系。 If you do this, you have to form the same relationship for view models, too. 如果这样做,您还必须为视图模型建立相同的关系。

So, I would like to share one parent model with child view model and parent view model without letting the parent view model have the child view models. 因此,我想与子视图模型和父视图模型共享一个父模型,而不让父视图模型具有子视图模型。

Could you all give any solutions to this problem? 你们能解决这个问题吗? Thank you. 谢谢。

Thank you for answering my question. 谢谢你回答我的问题。 I solved this problem, using the attached behavior for the parent view. 我使用父视图的附加行为解决了这个问题。 Here is what I did. 这就是我做的。

  1. I registered the custom property called "ChildModels", which binds ObservableCollection. 我注册了名为“ChildModels”的自定义属性,它绑定了ObservableCollection。
  2. I created the behavior called "OnChildModelsPropertyChanged" and make it trigger when the child models are given from the parent view model. 我创建了名为“OnChildModelsPropertyChanged”的行为,并在从父视图模型给出子模型时触发它。
  3. In the OnChildModelsPropertyChanged method, I created the same number of child view models as the child models and gave a child model to each child view model 在OnChildModelsPropertyChanged方法中,我创建了与子模型相同数量的子视图模型,并为每个子视图模型提供了子模型
  4. This created the relationship between the parent model and the child model without letting the parent view model and the child view model know each other. 这创建了父模型和子模型之间的关系,而不让父视图模型和子视图模型相互了解。

My explanation might sound really bad to you. 我的解释对你来说可能听起来很糟糕。 But this is pretty much all I did. 但这几乎就是我所做的一切。

Thank you for your answer again, and have a nice coding life!! 再次感谢您的回答,并拥有良好的编码生活!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM