Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

Navigating Between Pages

Although simple apps might have only one Page per window, most windows in real-world apps leverage multiple Pages. The XAML UI Framework contains quite a bit of functionality to make it easy to navigate from one page to another (and back), much like in a Web browser. Visual Studio templates also give you a lot of code in a Common folder to handle many small details, such as applying standard keyboard navigation to page navigation, and automatic integration of session state.

Although a Blank App project is given a single page by default, you can add more pages by right-clicking the project in Solution Explorer then selecting Add, New Item..., and one of the many Page choices. The different choices are mostly distinguished by different preconfigured layouts and controls.

In addition, if you create a Hub App project, it is already set up as an app with a multi-Page window. Figures 7.1 and 7.2 show the behavior of the Hub App project before any customizations are made. Separate Pages are provided for phone versus PC, which explains a number of differences in the content and style.

FIGURE 7.1

FIGURE 7.1 A Hub App project, shown here on a PC, contains three pages: one that shows sections, and one that shows the items inside each section, and one that shows item details.

FIGURE 7.2

FIGURE 7.2 A Hub App project, shown here on a phone, contains three pages: one that shows sections, and one that shows the items inside each section, and one that shows item details.

Selecting a certain section on the first Page (HubPage) automatically navigates to its details on the second page (SectionPage). Selecting an item in the section navigates to the third page (ItemPage). When the user clicks the back button in the corner of the window on a PC, or the hardware back button on a phone, the window navigates back to the previous page.

Basic Navigation and Passing Data

Although it’s natural to think of a Page as the root element of a window (especially for single-page windows), all Pages are contained in a Frame. Frame provides several members to enable Page-to-Page navigation. It is often accessed from the Frame property defined on each Page.

To navigate from one page to another, you call Frame’s Navigate method with the type (not an instance) of the destination page. An instance of the new page is automatically created and navigated to, complete with a standard Windows animation.

For example, when an item is clicked in a Hub App’s SectionPage, it navigates to a new instance of ItemPage as follows:

void ItemView_ItemClick(object sender, ItemClickEventArgs e)
{
  // Navigate to the appropriate destination page, configuring the new page
  // by passing required information as a navigation parameter
  var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;
  this.Frame.Navigate(typeof(ItemPage), itemId);
}

Navigate has two overloads, one that accepts only the type of the destination page, and one that also accepts a custom System.Object that gets passed along to the destination page. In this case, this second parameter is used to tell the second page which item was just clicked. If you use SuspensionManager in your project, its automatic management of navigation state means that whatever you pass as the custom Object for Navigate must be serializable.

The target ItemPage receives this custom parameter via the NavigationEventArgs instance passed to the Page’s OnNavigatedTo method. It exposes the object with its Parameter property.

A call to Navigate raises a sequence of events defined on Frame. First is Navigating, which happens before the navigation begins. It enables the handler to cancel navigation by setting the passed-in NavigatingCancelEventArgs instance’s Cancel property to true. Then, if it isn’t canceled, one of three events will be raised: Navigated if navigation completes successfully, NavigationFailed if it fails, or NavigationStopped if Navigate is called again before the current navigation finishes.

Page has three virtual methods that correspond to some of these events. OnNavigatingFrom enables the current page to cancel navigation. OnNavigatedFrom and OnNavigatedTo correspond to both ends of a successful navigation. If you want to respond to a navigation failure or get details about the error, you must handle the events on Frame.

Navigating Forward and Back

Just like a Web browser, the Frame maintains a back stack and a forward stack. In addition to the Navigate method, it exposes GoBack and GoForward methods. Table 7.1 explains the behavior of these three methods and their impact on the back and forward stacks.

TABLE 7.1 Navigation Effects on the Back and Forward Stacks

Action

Result

Navigate

Pushes the current page onto the back stack, empties the forward stack, and navigates to the desired page

GoBack

Pushes the current page onto the forward stack, pops a page off the back stack, and navigates to it

GoForward

Pushes the current page onto the back stack, pops a page off the forward stack, and navigates to it

GoBack throws an exception when the back stack is empty (which means you’re currently on the window’s initial page), and GoForward throws an exception when the forward stack is empty. If a piece of code is not certain what the states of these stacks are, it can check the Boolean CanGoBack and CanGoForward properties first. Frame also exposes a BackStackDepth readonly property that reveals the number of Pages currently on the back stack.

Therefore, you could imagine implementing Page-level GoBack and GoForward methods as follows:

void GoBack()
{
  if (this.Frame != null && this.Frame.CanGoBack) this.Frame.GoBack();
}

void GoForward()
{
  if (this.Frame != null && this.Frame.CanGoForward) this.Frame.GoForward();
}

For advanced scenarios, the entire back and forward stacks are exposed as BackStack and ForwardStack properties, which are both a list of PageStackEntry instances. With this, you can completely customize the navigation experience, and do things such as removing Pages from the back stack that are meant to be transient.

On a PC, apps with multiple pages typically provide a back button in the corner of the window. On a phone, apps should rely on the hardware back button instead. To respond to presses of the hardware back button, you attach a handler to a static BackPressed event on a phone-specific HardwareButtons class:

#if WINDOWS_PHONE_APP
  Windows.Phone.UI.Input.HardwareButtons.BackPressed +=
    HardwareButtons_BackPressed;
#endif

In your handler, you can perform the same GoBack logic shown earlier:

#if WINDOWS_PHONE_APP
void HardwareButtons_BackPressed(object sender,
  Windows.Phone.UI.Input.BackPressedEventArgs e)
{
  if (this.Frame != null && this.Frame.CanGoBack)
  {
    e.Handled = true;
    this.Frame.GoBack();
  }
}
#endif

Setting the BackPressedEventArgs instance’s Handled property to true is critical, as it disables the default behavior that closes your app. Here, that only happens once the back stack is empty.

Page Caching

By default, Page instances are not kept alive on the back and forward stacks; a new instance gets created when you call GoBack or GoForward. This means you must take care to remember and restore their state, although you will probably already have code to do this in order to properly handle suspension.

You can change this behavior on a Page-by-Page basis by setting Page’s NavigationCacheMode property to one of the following values:

  • Disabled—The default value that causes the page to be recreated every time.
  • Required—Keeps the page alive and uses this cached instance every time (for GoForward and GoBack, not for Navigate).
  • Enabled—Keeps the page alive and uses the cached instance only if the size of the Frame’s cache hasn’t been exceeded. This size is controlled by Frame’s CacheSize property. This property represents a number of Pages and is set to 10 by default.

Using Required or Enabled can result in excessive memory usage, and it can waste CPU cycles if an inactive Page on the stack is doing unnecessary work (such as having code running on a timer). Such pages can use the OnNavigatedFrom method to pause its processing and the OnNavigatedTo method to resume it, to help mitigate this problem.

When you navigate to a Page by calling Navigate, you get a new instance of it, regardless of NavigationCacheMode. No special relationship exists between two instances of a Page other than the fact that they happen to come from the same source code. You can leverage this by reusing the same type of Page for multiple levels of a navigation hierarchy, each one dynamically initialized to have the appropriate content. However, if you want every instance of the same page to act as if it’s the same page (and “remember” its data from the previously seen instance), then you need to manage this yourself, perhaps with static members on the relevant Page class.

NavigationHelper

If you add any Page more sophisticated than a Blank Page to your project, it uses a NavigationHelper class whose source also gets included in your project. For convenience, NavigationHelper defines GoBack and GoForward methods similar to the ones implemented earlier. It also adds phone-specific handling of the hardware back button, as well as standard keyboard and mouse shortcuts for navigation. It enables navigating back when the user presses Alt+Left and navigating forward when the user presses Alt+Right. For a mouse, it enables navigating back if XButton1 is pressed and forward if XButton2 is pressed. These two buttons are the browser-style previous and next buttons that appear on some mice.

NavigationHelper also hooks into some extra functionality exposed by SuspensionManager in order to automatically maintain navigation history as part of session state. To take advantage of this, you need to call one more method inside OnLaunched (or OnWindowCreated) to make SuspensionManager aware of the Frame:

var rootFrame = new Frame();
SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

Each Page should also call NavigationHelper’s OnNavigatedTo and OnNavigatedFrom methods from its overridden OnNavigatedTo and OnNavigatedFrom methods, respectively, and handle NavigationHelper’s LoadState and SaveState events for restoring/persisting state. LoadState handlers are passed the “navigation parameter” object (the second parameter passed to the call to Navigate, otherwise null) as well as the session state Dictionary. SaveState handlers are passed only the session state Dictionary.

When you create a Hub App project, all these changes are applied automatically. Internally, this works in part thanks to a pair of methods exposed by FrameGetNavigationState and SetNavigationState—that conveniently provide and accept a serialized string representation of navigation history.

Other Ways to Use Frame

Not every app needs to follow the pattern of a Window hosting a Frame that hosts Page(s). A Window’s content doesn’t have to be a Frame, and you can embed Frames anywhere UIElements can go. We can demonstrate this by modifying a Hub App project to set the Window’s Content to a custom Grid subclass that we create. Imagine this is called RootGrid, and it must be constructed with a Frame that it wants to dynamically add to its Children collection. It would be used in App.xaml.cs as follows:

// Instead of Window.Current.Content = rootFrame:
Window.Current.Content = new RootGrid(rootFrame);

RootGrid can be added to the project as a pair of XAML and code-behind, shown in Listings 7.3 and 7.4.

LISTING 7.3 RootGrid.xaml: A Simple Grid Expecting to Contain a Frame

<Grid x:Class="Chapter7.RootGrid" Background="Blue"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <!-- A 3x3 Grid -->
  <Grid.RowDefinitions>
    <RowDefinition/>
    <RowDefinition/>
    <RowDefinition/>
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition/>
    <ColumnDefinition/>
    <ColumnDefinition/>
  </Grid.ColumnDefinitions>
  <!-- Two Buttons to interact with a Frame -->
  <Button Name="BackButton" Grid.Row="1" HorizontalAlignment="Center"
    Click="BackButton_Click">Back</Button>
  <Button Name="ForwardButton" Grid.Row="1" Grid.Column="2"
    HorizontalAlignment="Center" Click="ForwardButton_Click">Forward</Button>
</Grid>

LISTING 7.4 RootGrid.xaml.cs: The Code-Behind That Places the Frame and Interacts with It

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace Chapter7
{
  public sealed partial class RootGrid : Grid
  {
    Frame frame;

    public RootGrid(Frame f)
    {
      InitializeComponent();
      this.frame = f;

      // Add the Frame to the middle cell of the Grid
      Grid.SetRow(this.frame, 1);
      Grid.SetColumn(this.frame, 1);
      this.Children.Add(this.frame);

      this.frame.Navigated += Frame_Navigated;
    }

    void Frame_Navigated(object sender, NavigationEventArgs e)
    {
      if (this.frame != null)
      {
        // Keep the enabled/disabled state of the buttons relevant
        this.BackButton.IsEnabled = this.frame.CanGoBack;
        this.ForwardButton.IsEnabled = this.frame.CanGoForward;
      }
    }

    void BackButton_Click(object sender, RoutedEventArgs e)
    {
      if (this.frame != null && this.frame.CanGoBack)
        this.frame.GoBack();
    }

    void ForwardButton_Click(object sender, RoutedEventArgs e)
    {
      if (this.frame != null && this.frame.CanGoForward)
        this.frame.GoForward();
    }
  }
}

By placing the Frame in its middle cell, RootGrid is effectively applying a thick blue border to the Frame that persists even as navigation happens within the Frame. (When used this way, Frame seems more like an iframe in HTML.) The simple back and forward Buttons in RootGrid are able to control the navigation (and enable/disable when appropriate) thanks to the APIs exposed on Frame. This unconventional window is shown in Figure 7.3, after navigating to the second page.

FIGURE 7.3

FIGURE 7.3 A Frame doesn’t have to occupy all the space in an app’s window.

Although this specific use of Frame doesn’t seem practical, you can do some neat things with a similar approach. One example would be to have a Page that always stays on screen containing a fullscreen Frame that navigates to various Pages. The reason this is compelling is that the outer Page can have app bars that are accessible regardless of what the current inner Page is. (App bars are discussed in Chapter 9, “Content Controls.”)

If you decide you want your Page to truly be the root content in your app’s Window, you can change the code in App.xaml.cs to eliminate the hosting Frame. This can work fine, but with no Frame, you don’t get the navigation features.

  • + Share This
  • 🔖 Save To Your Account