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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020