Messaging System in WPF

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.

publicinterface IListen { }

publicinterface IListen<T> : IListen

{

void Handle(T obj);

}

publicclass EventAggregator

{

private List<IListen> subscribers = new List<IListen>();

publicvoid Subscribe(IListen model)

{

this.subscribers.Add(model);

}

publicvoid Unsubscribe(IListen model)

{

this.subscribers.Remove(model);

}

publicvoid Publish<T>(T message)

{

foreach (var item inthis.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.