C# – Propagating Data to multiple ViewModels – C#

cmvcmvvm

I'm a bit new to MVVM, but here's my dilemma:

  1. I have a model (or models, but let's keep it simple)
  2. I want to show that model data on multiple different views.
  3. Ok, so ViewModel for each view gets created
  4. UserControls get created (my views)
  5. 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?

Best Answer

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.