I'm a bit new to MVVM, but here's my dilemma:
- I have a model (or models, but let's keep it simple)
- I want to show that model data on multiple different views.
- Ok, so ViewModel for each view gets created
- UserControls get created (my views)
- each Usercontrol gets a ViewModel
Here's my question: What/where/how do I handle propagating this model to each viewmodel?
This is desktop dev, not web dev, so I'm getting stuck on the idea of making sure that the model is in each viewmodel. Normally I handle this by having a controller/parent class propagate down the information to each ViewModel, but I'm starting to get into a more complex application where it's not one model that I need to propagate, but multiple models and viewmodels that might need to call services that would need that info as well, and I'm getting a bit confused as to how exactly the best practice is to proceed.
Just to be thorough, here's a quick example:
View1, View2, View3, and View4 all exist.
View1 and View2 need models M1, M2, and M3 View3 needs models M1, M3, and M4 View4 needs models M2, M3, M4, and M5
Each view now has it's own corresponding ViewModel, VM1-4.
How do I create and propagate M1-5 to the corresponding VMs?
2 Answers 2
I would suggest that you consider using an event aggregator pattern to achieve this.
An Event Aggregator acts as a single source of events for many objects. It registers for all the events of the many objects allowing clients to register with just the aggregator.
...
Event Aggregator is a good choice when you have lots of objects that are potential event sources. Rather than have the observer deal with registering with them all, you can centralize the registration logic to the Event Aggregator. As well as simplifying registration, a Event Aggregator also simplifies the memory management issues in using observers.
-
If you are using Windows Presentation Foundation (WPF) this can be found in the Caliburn.Micro framwork.Jakob Busk Sørensen– Jakob Busk Sørensen07/18/2019 07:07:40Commented Jul 18, 2019 at 7:07
"Dependency Injection" and "Inversion of Control" come into my mind. That is, you have some "container" which is responsible for creating the instances and injecting the dependencies.
In your case, you must make sure that only one instance per model is created. That can often be achieved by a "named instance".
In a "poor man's" scenario, you could do:
M1 m1 = new M1();
M2 m2 = new M2();
...
V1 v1 = new V1(m1, m2, m3);
... etc.
DataContext
object, which essentially contains all of the models. This is going to depend heavily on what your data access strategy looks like. Do you have a data access strategy?