Search code examples
c#wpfeventsmvvmeventaggregator

How does an EventAggregator register events and subscribers and notify all subscribers of events firing?


I read up on the EventAggregator pattern, specifically for MVVM and while I get the idea that one class registers an event within it and other classes can subscribe to that event and I've seen some interfaces I fail to imagine how the code would actually work.

How can you register an event and subscribe to it?
Furthermore how would subscribers be notified of an event's firing?

Thank you!


Solution

  • It depends on the implementation of the event aggregator.

    In Prism's version, you publish a MessageSentEvent (public class MessageSentEvent : PubSubEvent<string> {} ) like this:

    _eventAggregator.GetEvent<MessageSentEvent>().Publish("hello");
    

    ...and subscribe to it like this:

    _eventAggregator.GetEvent<MessageSentEvent>().Subscribe(message => MessageBox.Show(message));
    

    There is a full code example available on GitHub.

    The view model in ModuleA sends a message to the view model in ModuleB.