MVVM Light Messaging Made Absurdly Easy

I wanted to send a message from a ViewModel to its View so that themegaphone1 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");
 Messenger.Default.Send(myMessage);

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.

 

 

Share

About Jesse Liberty

Jesse Liberty is an independent consultant and programmer with three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight courses, and has been a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP, Microsoft MVP and Telerik MVP.
This entry was posted in Essentials. Bookmark the permalink.

One Response to MVVM Light Messaging Made Absurdly Easy

  1. Pingback: The Daily Six Pack: November 21, 2016 ⋆ Dirk Strauss' Tech Blog

Leave a Reply

Your email address will not be published.