Most MVVM frameworks come with some form of message bus. A means to send messages from one class to any classes wishing to listen for such messages. Ofcourse in a MVVM world those classes might be view models also.
In Caliburn Micro this message bus implementation is known as the event aggregator which is defined by the IEventAgreggator interface.
A class wishing to subscribe to events simple get passed an IEventAggregator as calls the subscribe method as follows
public MyViewModel(IEventAggregator eventAggregator) { eventAggregator.Subscribe(this); }
In this example we’re using the constructor and in this case, I’m using the Ninject bootstrapper which we looked at in a previous post, to inject the IEventAggregator into the constructor.
Obviously we need to add some code to actually handle any events as this solely subscribes to the aggregator, so for the sake of argument we’ll assume we have an event class which looks like the following
public class MyMessageEvent { public MyMessageEvent(string message) { Message = message; } public string Message { get; provate set; } }
And now on our view model we implement IHandle
public class MyViewModel : PropertyChangedBase, IHandle<MyMessageEvent> { public void Handle(MyMessageEvent message) { // do something with the event } }
Now we need something to publish events…
If we create another view model and again pass the IEventAggregator into the constructor as per
public class MyViewModel : PropertyChangedBase { private IEventAggregator eventAggregator; public MyViewModel(IEventAggregator eventAggregator) { this.eventAggregator = eventAggregator; } public void PublishMessage() { event.Publish(new MyMessageEvent("Hello")); } }