Windows Phone 7 - Navigation between pages using MVVM Light Messaging

20 July 2010

Introduction

This post will get you started with being able to set up navigation between pages within your Windows Phone 7 (WP7) application using the core messaging framework provided by MVVM Light.

Read our Windows Phone 7 - mvvm Light and Unit Testing Example to understand a little more about MVVM Light if you are not familiar with the framework. Also check out our Windows Phone 7 - mvvm Light Messaging and Dynamic Application Bar post for another messaging example.

System Requirements

I’ve checked every thing against the latest public beta release of the devel oper tools (as of 15/07/2010) from http://developer.windowsphone.com. Please make sure you have this installed. I’m using Visual Studio 2010, but it all should work ok with Visual Studio Express 2010 that comes with the developer tools.

Navigation as a View related concern

Within your View Model you often reach points where you want to instigate a navigation to another page within your application. A primary urge is to simply perform the navigation within the view model. However, as page navigation is a View related concern, it is better handled at that end where there is an active navigation context rather than within the View Model.

Send a message from the View Model

Put this code in your ViewModelBase class to ensure you have an easy way to send out a request for a navigation change using the MVVM Light Messaging framework.

protected void SendNavigationRequestMessage(Uri uri)
{
    Messenger.Default.Send<Uri>(uri, "NavigationRequest");
}

Then in your xaml page code behind (or your own custom base PhoneApplicationPage class) you can place a single line of code to perform the navigation request

Messenger.Default.Register<Uri>(this, "NavigationRequest", (uri) => NavigationService.Navigate(uri));

Conclusion

Using a messaging approach like that provided with MVVM Light helps keep your WP7 application loosely coupled. The View can remain focussed on view specific concerns and can interact with your View Model indirectly using messaging to avoid hard wiring the two together unnecessarily. For a quick and easy solution to navigation within your application, this can work well.

Want to get started?

We would love to help with your next app or game, please do get in touch.