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);
- }
- }
- }
To demonstrate this example let's use a class Car that will listen for signals and a class Guard that will notify the cars using a SignalMessage class.
- 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; }
- }
Run this application.
- 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);
- }
We will see that all the cards are being notified: