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?

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

One Response to View Model Page Navigation with MVVM Light

Comments are closed.