View Model Page Navigation with MVVM Light

When you move from code behind to a View Model (as you should, if only to makeBlank freeway sign ready for your custom text testing easier) certain challenges arise, such as: how do I navigate to another page?

Fortunately, MVVM Light provides a Messaging bus, that makes it easy to send messages from a View Model to a page (or to another View Model).  This can be over done but when used judiciously it makes the very difficult into the very easy.

The following solution was improved enormously by Eric Grover, my favorite MVVM Light Guru after Laurent 🙂

Begin by creating a parent for ContentPage (I called mine BaseViewPage).  Have your content pages derive from the new page.  In the new page we’ll register to receive Navigation Messages from the Messenger Bus

 

public BaseViewPage( )
  {
 
      Messenger.Default.Register<INavigationMessage>(
          this,
          HandleNavigation );
 
  }

Notice we need an interface, INavigationMessage and a method, HandleNavigation.

INavigationManager looks like this:

 

public interface INavigationMessage
  {
      Type PageType { get;  }
  }

This allows us to navigate to any type of page.  Its implementation is:

public class NavigationMessage<T> : INavigationMessage where T : Page
{
    public Type PageType
    {
        get { return typeof(T); }
    }
 
}

This nicely forces the type to be a Page.

Here’s HandleNavigation, which also goes in the BaseViewPage:

 

public async void HandleNavigation( 
    INavigationMessage navigationMessage )
   {
 
       var target = Activator.CreateInstance(
               navigationMessage.PageType);
 
       await Navigation.PushAsync( (ContentPage) target );
   }

Nicely generic, which is just what we want.

Now we’re ready to use this.  Let’s say we’re in MyPageViewModel and we want to navigate to YourPage (xaml).  We write:

 

var message = new NavigationMessage<YourPage>();
Messenger.Default.Send( message );

Slick, eh?

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 Xamarin. Bookmark the permalink.

One Response to View Model Page Navigation with MVVM Light

  1. Matt says:

    Wow, Thanks Jesse. This is exactly what I was looking for.

    Keep up the great posts!

Leave a Reply

Your email address will not be published.