WP7 Navigation in depth | Navigation Framework
published on: 11/24/2010 | Views: N/A | Tags: Navigation
by WindowsPhoneGeek
In the "WP7 Navigation in depth" series of two articles I am going to talk about the different Windows Phone 7 page navigation scenarios in depth.
"WP7 Navigation in depth | Navigation Framework" - I will explain the basic usage and all about the available public API in depth.
"WP7 Navigation in depth | Navigation controls" - I will talk about using different navigation controls.
In this article I will explain in details all you need to know about the WP7 Navigation framework. To begin with lets first define a sample WP7 App project and add some pages: MainPage.xaml, Pahe1.xaml and Page2.xaml. I will use these pages in order to demonstrate different ways of page navigation.
Windows Phone applications are based on a Silverlight page model where users can navigate forward through different screens of content. Also, you can move backward using the Windows Phone "back" hardware button. This model enables developers to:
-
Easily create view-based applications that fit naturally into the Windows Phone navigation model
-
Provide default transitions that match the Windows Phone look and feel
Generally the windows phone 7 navigation is based on a frame/page model:
Note: You must use the PhoneApplicationFrame and PhoneApplicationPage types when developing your application and not the standard Silverlight Frame and Page types.
PhoneApplicationFrame
Only a single frame is available to the application with no exceptions. It contains the Page control and another elements like system tray and application bar. A frame includes the following characteristics:
-
Exposes properties from a hosted page such as screen orientation
-
Exposes a client area where pages are rendered
-
Reserves space for the system tray and application bar
PhoneApplicationPage
A page fills the entire content region of the frame. It includes the following characteristics:
-
Optionally surfaces its own application bar
There are three main ways to navigate between pages in your app:
- Using the PhoneApplicationPage virtual methods for handling the result of navigation.
- HyperlinkButton - it provides NavigateUri property which can be used to navigate to a page Uri.
- NavigationService - it provides methods, properties, and events to support navigation within a wp7 application.
Note: The PhoneApplicationPage class supports OnNavigatedTo, OnNavigatedFrom and OnNavigatingFrom virtual methods for handling the result of navigation:
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
// some code here
}
Note: Make sure that the Root of your application is set to the PhoneApplicationFrame(this is set by default to every wp7 app project). The code is usually placed in the App.xaml.cs and the code looks like:
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
Once your frame is created, the runtime navigates to a startup page. In WP7 the situation is a little bit different than in Silverlight. Instead of setting the startup page in App.xaml.cs the WP7 uses WMAppManifest.xaml file which contains the so called tasks. Just go to Properties folder and select WMAppManifest.xaml as shown in the sample screen shot. The task section looks like:
<Tasks> <DefaultTask Name ="_default" NavigationPage="MainPage.xaml"/> </Tasks>
Here is the place where you can change the start up page using the NavigationPage property.
HyperlinkButton
This is the easiest way to set up navigation. All you need to do is just to create a hyperlink button on one page and set the NavigateUri property to the name of the page that you want to navigate to. Lets make a page called Page1.xaml in the main root of the project. The code for accomplishing this is as follows:
<HyperlinkButton Content="HyperlinkButton" NavigateUri="/Page1.xaml"/>
Note: HyperlinkButton only navigates between pages. You can use WebBrowserTask to navigate to web uris .
NavigationService
If you need a more flexible way of navigation then use the NavigationService class. This class contains a number of methods, events and properties to help you make your navigation.The NavigationService exists on the Application and Page classes.
Key Methods
- GoBack() - Navigates to the most recent entry in the back navigation history, or throws an exception if no entry exists in back navigation.
- GoForward() - Navigates to the most recent entry in the forward navigation history, or throws an exception if no entry exists in forward navigation.
- Navigate(Uri) - Navigates to the content specified by the uniform resource identifier (URI).
Note:Although the GoBack() method was utilized in this example, the hardware back key would also have the effect of returning to the previous page.
Key Properties
- CanGoBack - Gets a value that indicates whether there is at least one entry in the back navigation history.
- CanGoForward - Gets a value that indicates whether there is at least one entry in the forward navigation history.
- CurrentSource - Gets the uniform resource identifier (URI) of the content that is currently displayed.
- Source - Gets or sets the uniform resource identifier (URI) of the current content or the content that is being navigated to.
Note:For Windows Phone GoForward() will always throw an exception because there is no forward navigation stack.
Key Events
- FragmentNavigation - Occurs when navigation to a content fragment begins.
- Navigated - Occurs when the content that is being navigated to has been found and is available.
- Navigating - Occurs when a new navigation is requested.
Lets say that we want to navigate to Page1.xaml when clicking on a button and after that return back to MainPage.xaml using the NavigationServoce API. The code for accomplishing this is as follows:
MainPage.cs
private void btnPage1_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
}
Page1.cs
private void btnBack_Click(object sender, RoutedEventArgs e)
{
if (this.NavigationService.CanGoBack)
{
NavigationService.GoBack();
}
}
Passing Data between Pages
When we want to pass some data between pages we have to :
- form a query string
- use the NavigationContext.
The NavigationContext exists on the Application and Page classes. The purpose of this class is to expose the query string of the navigation URI so that we can use it to pass parameters between pages while navigating in an easy way.
The code is as follows:
MainPage.cs
string parameter = "Passing Parameter Test";
NavigationService.Navigate(new Uri(string.Format("/Page2.xaml?parameter={0}", parameter), UriKind.Relative));
In this case we have a string parameter in MainPage and want to pass it to Page2. When we reach the navigated page the NavigationContext is used to retrieve the specific information about the passing parameter. The code is as follows:
Page2.cs
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string newparameter = this.NavigationContext.QueryString["parameter"];
this.textLabel.Text = newparameter;
}
Note: It is important to override the OnNavigatedTo and after that you can use the NavigationContext.
Another popular syntax is :
string parameter = string.Empty;
if (NavigationContext.QueryString.TryGetValue("parameter", out parameter))
{
this.textLabel.Text = parameter;
}
That was all about the navigation framework and the end of "WP7 Navigation in depth | Navigation Framework" article. In the next post "WP7 Navigation in depth | Navigation controls" I will talk about using different navigation controls.
The full source code is available here:
I hope that the article was helpful.
You can also follow us on Twitter @winphonegeek
Comments
A clarification - Forward navigation is not supported
posted by: Daniel Vaughan on 11/25/2010 2:18:16 AM
Hi,
Thank you for posting.
I have one clarification for your readers. Silverlight for Windows Phone 7 does not support forward navigation. The NavigationService.CanGoForward will always return false, and, in fact, if you attempt to navigate forward an exception will be raised.
Cheers, Daniel
http://danielvaughan.orpius.com @dbvaughan
Thanks! Very helpful
posted by: Girish Jain on 2/15/2011 7:18:41 PM
Hi, This was really very helpful. There is not much content available over internet or MSDN for Silverlight on WP7, your article is helpful
Passing objects between pages.
posted by: mike on 3/10/2011 3:15:09 AM
This is a good article, but I have a question about passing class data between pages.
I have created an employee class which contain information about the employee. This is in a class.cs file wich all my pages can use to instatiated their own employee objects but I can't figure out a way to let another page see the others employee's.
I am really trying to make a global list that each page can see and manipulate as needed. Putting the data in a listbox and using navigation is not what I need to do. Something like "list
Thanks, Mike
hi
posted by: bindu on 3/28/2011 1:48:03 PM
hi ur article is a summary of all the data i could find across net while surfing. i have got a doubt.
i am writing an app where in i want the user to login. the login screen is a pop up page (i have used a user control page). i am unable to use the NavigationService as it is throwing an error "An object reference is required for the non-static field, method, or property 'System.Windows.Navigation.NavigationService.Navigate(System.Uri)'" i wish to navigate to some page in the app kindly help me
RE: @mike, @bindu
posted by: winphonegeek on 4/26/2011 11:07:26 PM
@mike one approach to implement global application state is to have a property on your application class and then access it through Application.Current (of course you will have to cast to your application class).
@bindu what you are seeing is probably a compile error caused by the fact that the Navigate method is an instance method and not a static one. In order to use it you will need a NavigationService instance which can be obtained through the NavigationService instance property of the Page class.
hai
posted by: varaprasad rapaka on 6/28/2011 9:18:59 AM
iam trainee it is helpful but give a real application using navigation.
@varaprasad
posted by: winphonegeek on 6/28/2011 3:43:40 PM
You can also take a look at our post: WP7 Master - Detail Navigation with Repository Pattern
A better WP7 navigation alternative
posted by: Adrian Aisemberg on 7/5/2011 1:29:52 PM
Kick-ass WP7 navigation without passing any strings. Any object type is supported: Easy Windows Phone 7 Navigation
full source code missing
posted by: jon on 9/8/2011 11:26:57 AM
can u please repost the full source code
RE:full source code missing
posted by: winphonegeek on 9/8/2011 1:10:26 PM
We just re uploaded the source. You can download it now.
ListBox and Navigation
posted by: Amparo on 10/15/2011 1:14:30 PM
Hi!
I'm very new in programming wp7 so I hope you can help me.
In my MainPage I have a ListBox with all the information I get from a xml file. I have a SelectionChanged method programmed and I pass to the second page the index selected from de ListBox, I then catch it in the second page, but what I want is to get de string that I have in the listbox and not just the index.
Could you give an idea of how to do it.
Thanks a lot.
Amparo
ListBox and Navigation
posted by: Amparo on 10/16/2011 9:24:32 PM
Solved!! :)
Our Top Articles & Free books
- Our FREE e-book: "Windows Phone Toolkit In Depth" 2nd edition
- 400+ Windows Phone Development articles in our Article Index
- 21 WP7 Toolkit in Depth articles covering all controls
- 12 WP7 Coding4Fun Toolkit in Depth articles covering all controls
- Performance Tips when creating WP7 apps
- Creating a WP7 Custom Control in 7 Steps
- WP7 working with VisualStates: How to make a ToggleSwitch from CheckBox
- What makes a WP7 App successful
- Creating theme friendly UI in WP7 using OpacityMask
- Implementing Windows Phone 7 DataTemplateSelector and CustomDataTemplateSelector
- All about Splash Screens in WP7 – Creating animated Splash Screen
- Getting Started with Unit Testing in Silverlight for WP7
- WP7 WatermarkedTextBox custom control
Our Top Tips & Samples
- All about WP7 Isolated Storage series
- WP7 Dynamically Generating DataTemplate in code
- 5 tips for a successful WP7 Marketplace submission
- WP7: Navigating to a page in different assembly
- WP7 ContextMenu: answers to popular questions
- WP7 ListBox: answers to popular questions
- WP7 working with Images: Content vs Resource build action
- WP7 Element Binding samples
- WP7 working with XML: reading, filtering and databinding
- Drawing in WP7: #2 Drawing shapes with finger
- WP7 TextBox Light theme problems - the solution
- Changing the WP7 Panorama Background Image dynamically with Animation
