Reputation: 828
One of my views contains a dropdown menu. When a selection is made, its view model and all other view models in the program must be made aware of the change so that they can update their views. Currently each view model contains its own copy of the selection and when it is changed I have to manually update them all (I just have a public Refresh(int newVal) on each one). Is there a better way of doing this?
Upvotes: 0
Views: 248
Reputation: 4632
A possible approach might be to use an event aggregator. The aggregator is used to dispatch the messages between the publishers and receivers.
The objects that need to send a message register the message type with the EventAggregator
and the objects that need to receive subscribe for them also at the EventAggregator
.
There are many ways to implement this, I suggest using any MVVM framework of your choice. Most common frameworks offer time-proven implementations of this.
An example would be Caliburn Micro. CM framework already offers the EventAgregator
class for this.
See an example of this here:Introduction to messaging with Caliburn.Micro’s EventAggregator.
Upvotes: 1
Reputation: 3538
Use an (aggregated) event.
Subscribe to the event when the view is loaded, unsubscribe when the view is unloaded and make sure to initialize the variables in your view model when it's loaded. Then publish the event (pass the new data as a parameter) when the selection changes.
Upvotes: 1
Reputation: 1342
You could use an event aggregator and publish an event through it that could be handled by every view model (maybe in some kind of base class?).
Upvotes: 1