简体   繁体   中英

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

I am currently working on developing an application, using WPF and MVVM design pattern. 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.
  2. I created the behavior called "OnChildModelsPropertyChanged" and make it trigger when the child models are given from the parent view model.
  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
  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!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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