In WPF MVVM we might want to send a message from one View Model to another. For example, if we want to close a window and return data to the opener window. To allow such data exchange we can use a messaging system.
For that we have the EventAggregator pattern.
The EventAggregator class will store all the instances that are being tracked. So when a message is published all those listed instances will be notified.
- public interface IListen { }
- public interface IListen<T> : IListen
- {
- void Handle(T obj);
- }
- public class EventAggregator
- {
- private List<IListen> subscribers = new List<IListen>();
- public void Subscribe(IListen model)
- {
- this.subscribers.Add(model);
- }
- public void Unsubscribe(IListen model)
- {
- this.subscribers.Remove(model);
- }
- public void Publish<T>(T message)
- {
- foreach (var item in this.subscribers.OfType<IListen<T>>())
- {
- item.Handle(message);
- }
- }
- }
- public class Car : IListen<SignalMessage>
- {
- public Car(EventAggregator eventAggregator)
- {
- eventAggregator.Subscribe(this);
- }
- public void Handle(SignalMessage obj)
- {
- Console.WriteLine("I'm a car and a guard is telling me to stop!");
- }
- }
- public class Guard
- {
- private EventAggregator eventAggregator;
- public Guard(EventAggregator eventAggregator)
- {
- this.eventAggregator = eventAggregator;
- }
- public void SignalCars()
- {
- this.eventAggregator.Publish(new SignalMessage { Message = "Stop" });
- }
- }
- public class SignalMessage
- {
- public string Message { get; set; }
- }
- static void Main(string[] args)
- {
- var eventAggregator = new EventAggregator();
- var car1 = new Car(eventAggregator);
- var car2 = new Car(eventAggregator);
- var car3 = new Car(eventAggregator);
- var guard = new Guard(eventAggregator);
- guard.SignalCars();
- Console.ReadKey(true);
- }


Alex MiaffoPosted Apr 14, 2016, 7:00 AM
Nice. But what happens if our viewmodels will be created at different places instead of in the main as illustrated here? Let us say that I have a engingusercontrol in my carusercontrol and we want to notify the guard when the engineusercontrol button is clicked? Thanks
NitinPosted May 30, 2015, 10:19 AM
Nice
Atul GuptaPosted May 29, 2015, 6:01 AM
Nice, thaks for Sharing !
Santhakumar MunuswamyPosted May 29, 2015, 3:30 AM
Good
Sibeesh VenuPosted May 28, 2015, 6:57 AM
Good one.
Gowtham RajamanickamPosted May 28, 2015, 3:57 AM
good