Windows Phone From Scratch #18 – MVVM Light Toolkit Soup To Nuts 3

This is the third part of the MVVM Light Toollkit Soup To Nuts (part 1 is here) withinwhisper the Windows Phone From Scratch Mini-tutorial series.  Today we look at an introduction to messaging as a tool for communicating, e.g., from the view-model to the view.

What We’ll Build

To illustrate this, we’ll return to the example we began in part 1, and extended in part 2 (you can download the part 2 source code here).  As you’ll remember, we were able to convert the click event on the button on MainPage to be a command that is handled in Page 2. 

We stubbed out the handling of that command, but now it is time to complete the logic, by having the view model cause a navigation from MainPage to Page 2.  Unfortunately, the service that we need (NavigationService) is not available in the view model, and the easiest thing to do is to signal MainPage to make the transition. 

There is and should be no visibility of a view from a view-model, however, and so we need a mechanism for sending out a message in a bottle to be picked up by anyone who is interested. Specifically, we want the view model to be able to send a message indicating that it’s time to navigate to page 2. Further we want main page to register to receive that message, and on receipt, to invoke the navigation service to effect the transition to page 2.

Messaging

Fortunately, the MVVM Light Toolkit provides extensive support for messaging.  To accomplish our goals will require a fairly straightforward three-step process:

  1. Create a class to contain the message that is to be passed
  2. In the view model, instantiate the message class and broadcast the message
  3. Within MainPage.xaml.cs register for the message and handle it when received

Begin by creating a new class in the project in Visual Studio, and call the new class GoToPageMessage

using System;

namespace MvvmLightNavigationBehaviorAndMessages
{
   public class GoToPageMessage
   {
      public string PageName { get; set; }
   }
}

 

Return to MainViewModel.cs and remove the contents of the GoToPage2 method. Create an instance of the GoToPageMessage (initializing the PageName with the name of the page you want to navigate to) and use the Messenger object to broadcast the message, as shown here,

private object GoToPage2()
{
   var msg = new GoToPageMessage() { PageName = "Page2" };
   Messenger.Default.Send<GoToPageMessage>( msg );
   return null;
}

 

You’ll need to include the supporting library,

using GalaSoft.MvvmLight.Messaging;

 

This broadcasts the message, all that is left is to register a recipient and to respond to the message.  To do that, return to MainPage.xaml.cs, and register for the message in the constructor or in the MainPage_Loaded event handler,

Messenger.Default.Register<GoToPageMessage>
( 
     this, 
     ( action ) => ReceiveMessage( action ) 
);

 

You will need to add the Messaging using statement as well as a using statement for System.Text

ReceiveMessage is a method that you’ll write that will take the PageName and assemble a Navigate statement,

private object ReceiveMessage( GoToPageMessage action )
{
   StringBuilder sb = new StringBuilder( "/Views/" );
   sb.Append( action.PageName );
   sb.Append( ".xaml" );
   NavigationService.Navigate( 
      new System.Uri( sb.ToString(), 
            System.UriKind.Relative ) );
   return null;
}

 

Build and run the application. Clicking on the button on MainPage will now cause the application to navigate to Page 2.

So, Is This Easier??

No one would argue that what I’ve shown here is easier than simply handling the click-event in the code-behind. What I would argue is that this is easier to test because the programmer created logic is now in the view-model rather than in the code behind.

In any case, the use of behaviors and messaging goes well beyond this use-case, as we’ll see in coming tutorials.

You can download the final source code here.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was 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 Microsoft MVP.
This entry was posted in Data, Mini-Tutorial, Patterns & Skills, WindowsPhone and tagged . Bookmark the permalink.

21 Responses to Windows Phone From Scratch #18 – MVVM Light Toolkit Soup To Nuts 3

Comments are closed.