Calling Navigate From The View Model

Windows Phone Mini-Tutorial

In the third part of the MVVM Light Toolkit Soup To Nuts (part 1 is here) I started with an application that had two pages, and a button on the first that was to cause a navigation to the second page.  You can download the starting source code here

In that article I explained how the VM cannot call the Navigate service, but that you could use messaging to have the View make the call.  While that is correct, there is an easier way; which is to grab the rootFrame and to call Navigate on that.

To do this, open the starting application and navigate to the GoToPage2() method that is called by the relay command.  Remove the MessageBox and instead add this line to obtain the RootFrame of the current application,

var rootFrame = (App.Current as App).RootFrame;

Once you have that in hand, you can call the navigation service directly from the View Model,

 

rootFrame.Navigate( 
  new System.Uri( "/Views/Page2.xaml", System.UriKind.Relative ));

This greatly simplifies the code and avoids the added complexity of using messaging back to the original page to perform the navigation.

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 Pluralsight & LinkedIn Learning courses. 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 Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in Mango, Mini-Tutorial, Patterns & Skills and tagged . Bookmark the permalink.

12 Responses to Calling Navigate From The View Model

  1. Pingback: 在ViewModel中如何使用Navigate? | Tmango

  2. Pingback: WindowsDevNews.com

Comments are closed.