Home > C#, MVVM, Windows Phone, WinRT > How to send string and content messages with MVVM Light Messenger

How to send string and content messages with MVVM Light Messenger

25/06/2014

The Messenger component of MVVM Light easily allows to pass data between classes of our app:

// Sends a message with a Person object.
var person = new Person { FirstName = "Marco", LastName = "Minerva" };
Messenger.Default.Send(person);

// Registers for incoming Person messages.
Messenger.Default.Register<Person>(this, (person) =>
{
    // Works with the Person object.
});

To send an object, we simply need to pass it to the Messenger.Send method. But what if we just want to send string messages, like GotoDetailsPage or CloseApp?

In this case, we don’t want to create a new class only to pass a string. We can instead use the NotificationMessage object that comes with MVVM Light:

// Sends a notification message with a string content.
Messenger.Default.Send(new NotificationMessage("GotoDetailsPage"));

// Registers for incoming Notification messages.
Messenger.Default.Register<NotificationMessage>(this, (message) =>
{
    // Checks the actual content of the message.
    switch (message.Notification)
    {
        case "GotoDetailsPage":
            break;

        case "OtherMessage":
            break;

        default:
            break;
    }
});

At lines 8-18, we check the Notification property to determine the specific message that has been sent. Of course, we can use constants to avoid the repetition of string values.

We have also a generic version of NotificationMessage that we can use when we want to send an object along with a string message, which for example specifies the action that we want to perform:

// Sends a notification message with a Person as content.
var person = new Person { FirstName = "Marco", LastName = "Minerva" };
Messenger.Default.Send(new NotificationMessage<Person>(person, "Select"));

// Registers for incoming Notification messages.
Messenger.Default.Register<NotificationMessage<Person>>(this, (message) =>
{
    // Gets the Person object.
    var person = message.Content;

    // Checks the associated action.
    switch (message.Notification)
    {
        case "Select":
            break;

        case "Delete":
            break;

        default:
            break;
    }
});

The generic version of NotificationMessage exposes a Content property that contains the actual object. So we can retrieve it and use the Notification value to determine which action to execute.

Categories: C#, MVVM, Windows Phone, WinRT
Comments are closed.
%d bloggers like this: