I wanted to send a message from a ViewModel to its View so that the View could pop up a dialog box. To do this, I used MVVM Light’s messaging bus.
At first, this seemed difficult because I was over thinking it. It turns out to be painfully easy.
In the ViewModel I created a NotificaitonMessage. You can pass any kind of object through the Message Bus, but to keep things simple, I used a string as my token. All I had to do was instantiate a NotificationMessage object and then call a static method on the supplied Messenger class:
var myMessage = new NotificationMessage("change");
This sends off my message like a message in a bottle. The sender (my ViewModel) has no idea if the message will be received by any other class (ViewModel or View).
In the View I registered to receive this notification. To do so, I put one line in my constructor,
Messenger.Default.Register<NotificationMessage> (this, NotifyMe);
NotifyMe is a delegate, pointing to a method named NotifyMe. You could, of course, just use a lambda expression.
NotifyMe receives a parameter of type NotificationMessage. That message has a property Notification which contains the object you sent (e.g., “change”).
public void NotifyMe (NotificationMessage message)
string token = message.Notification; // "change"
DisplayAlert ("Test", "Hi!", "OK");
In the code shown, I extract the string “change” but I don’t do anything with it. I just extracted it to show how it is done.
That’s it. I’ve successfully told the View to display an alert by firing off a message in the ViewModel. Handy, quick, easy.