Tuesday, 6 August 2013

Windows Phone - Navigation from App.xaml.cs

To navigate to pages win windows phone app we use the Navigate method of NavigationService class:
NavigationService.Navigate(new Uri("/MyPage.xaml", UriKind.RelativeOrAbsolute));
But this doesn't work within App.xaml.cs.
Instead it works by using the below code:
Solution:
(Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/MyPage.xaml", UriKind.RelativeOrAbsolute));

Explanation:
Each application has only one Frame. It's this frame that exposes the NavigationService. Therefore, the NavigationService is always accessible via the frame since there's always an instance of it in any Windows Phone app. Since you don't usually instantiate a new NavigationService, it's easy to think that it's a static method. However, it's actually a non-static class that gets instantiated automatically when your app is run. All you're doing in this case is getting the global instance, which is attached to the always-present Frame, and using that to navigate between pages. This means your class does not have to instantiate, or explicitly inherit, a NavigationService.

No comments:

Post a Comment