April 2011

Volume 26 Number 04

Mobile Matters - Windows Phone Navigation, Part 2: Advanced Recipes

By Yochay Kiriaty | April 2011

[This concludes the first installment of MSDN Magazine*’s newest monthly column, Mobile Matters. With the growing importance of mobile technologies such as Windows Phone 7, we’ll regularly feature experts giving practical, hands-on advice to developers of all levels who want to increase their skills in this crucial technology space. We encourage you to help us shape our new column as we move forward. Please e-mail us at mmeditor@microsoft.com to suggest topics, share ideas or ask questions. We welcome all feedback.—Ed.*]

Last month we introduced you to the Windows Phone navigation model and related APIs (see msdn.microsoft.com/magazine/gg650662). Now we’ll share tips and tricks to accomplish more advanced navigation tasks. We’ll address the following aspects of Windows Phone:

  • Using the navigation APIs, you can use the Navigate and GoBack methods. These two methods either push or pop a URL to the navigation history (back stack). Because there are no APIs to manage the back stack, you have to manage transient screens yourself. Transient screens are dialogs or prompts that you don’t want users to revisit when they hit Back—for example, a message prompt or a login dialog.
  • Windows Phone allows only one navigation to be active at a time. If you need the “take me home” feature, which is usually a shortcut for a user to navigate back by multiple pages, you’ll have to serialize the sequence of GoBack method calls one at a time; this can affect your UX.
  • Neither of the two navigation participants—PhoneApplicationPage and PhoneApplicationFrame—have out-of-the-box support for page transitions.

Let’s dissect these aspects so we can arrive at actionable recipes to address them.

Transient Content

Transient screens are screens that shouldn’t be added to the journaling back stack (the journaling history)—for example, a login dialog. Users navigate from a page to a login dialog, but when they move forward and hit Back, you don’t want users to go back to the dialog, you want them to go back to the previous screen.

There are multiple ways to create and display a transient screen. The obvious one is to use a Silverlight Popup to show the UI. There are two small issues with the Popup approach:

  1. A Popup isn’t orientation-aware.  This isn’t a huge problem; you could write an orientation-aware Popup or you could just insert the Popup into the visual tree and it would then do layout according to the page orientation.
  2. Content inside a full-screen Popup isn’t hardware-accelerated. For the login dialog UI (and for many transient pages) this will be fine, but imagine where the Popup has a ListBox with enough items to scroll through, or it has an animated ProgressBar—you’ll want to hardware accelerate the Popup to maximize your UI thread’s responsiveness.

Because of these small issues, we recommend you inline the UI by inserting it into the visual tree with a higher z-index than the content of the page you’re in. Here’s the step-by-step recipe:

  1. Package the content you want to inline into the visual tree in a User control so you can insert it into the tree and show it in your page (without it being mixed into the UI of your page).
  2. In the PhoneApplicationPage that will show the UI, handle the OnBackKeyPress callback or the BackKeyPress event to dismiss the transient UI (without navigating back) when the Back button is pressed.
    1. Custom controls that have multiple states (expanded and collapsed) should expose properties so that the host page can query into their state and know if they’re in a state that can consume the Back button press (if applicable). For example, ListPicker on the control toolkit has a ListPickerMode property, ContextMenu has an IsOpen property and so on.
  3. Hide the ApplicationBar in the page when displaying the transient UI (if applicable). The ApplicationBar is drawn by the OS and when it’s Opaque (Opacity = 1.0) it reserves space below the content area for your page. To simulate your transient UI as being a new screen, you likely want to hide the application bar.
  4. Animate the transient UI when it transitions in and when it’s dismissed so that it blends with the rest of your application’s UX (if applicable).

Code walkthrough: To see a transient UI screen, check TransientUISample.xaml.cs in the accompanying code download, with step-by-step instructions as comments.

Most of the preceding requirements should be intuitive; the only one that needs explanation is No. 2.a. To meet the certification requirements, a PhoneApplicationPage showing a transient screen shouldn’t navigate back when the transient UI is showing. Instead, it should dismiss the transient UI.

In part 1 of this article, we mentioned that you should prevent hardware Back navigations by handling OnBackKeyPress or the BackKeyPress event. If your page is hosting a control that has two states and one of them is transient, then a bit of coordination (or at least awareness) between the page and the control is required. To implement the handshake, we recommend:

  1. Custom controls that have multiple states (for example, ListPicker) should subscribe to BackKeyPress on their hosting page and handle it appropriately. If they’re in a transient state, they should cancel the Back key press and dismiss their transient state.
    1. These controls should subscribe only when needed. Delay subscription to the BackKeyPress event until needed.
    2. We prefer the controls walk up the visual tree to find their PhoneApplicationPage, but we’ve seen experts (for example, the control toolkit team) do it by reaching out to the Application RootVisual (which we know is a PhoneApplicationFrame) and peeking into its content. This is, of course, more performant and still safe because we know there’s only one UI thread in a Silverlight app (so it’s unlikely the RootVisual is changing inside an event handler for your control or your page).
  2. Custom controls and transient UIs should expose properties so that the host page can query into their state and know if they’re in a state that can consume the Back button press. For example, ListPicker on the control toolkit has a ListPickerMode property, ContextMenu has an IsOpen property and so on.   
  3. Your host PhoneApplicationPage will need to be aware of any transient controls or UI that can be displayed and check on all of these before it does any navigation within OnBackKeyPress.  Remember, OnBackKeyPress is called before any handlers to BackKeyPress event are called. If you’re relying on the hosted controls to handle their transient state, make sure you don’t call the Navigate method and get ahead of the handlers.

Home Button Navigation (and Clearing the Back Stack)

A common UX pattern for other mobile platforms is to have a “Home” button that shortcuts navigation and sends you to a specific page. The Windows Phone navigation APIs don’t directly handle this; in fact, the UX guidelines strongly discourage having a Home button. The recommendation is to have a well-designed, relatively flat navigation structure. If your navigations are two or three levels deep, it’s probably just as easy to press the hardware Back button a couple times as it is to make a more calculated gesture finding a Home button on the screen and clicking it. That said, if you choose to have a Home button, there are a few things you must consider to implement the navigation:

  • Remember that Windows Phone allows one navigation at a time. This means if you’re four levels deep in a navigation, you’ll have to call GoBack three times in a row to get home. Because concurrent navigations aren’t allowed, you must wait until a navigation is completed (when the Navigated event fires) to start the next navigation. This “navigation sequence” can lead to brief delays if your page is taking a lot of time to load, or it can lead to “flickers” if your page is visible while you pop the back stack.
  • The animations for the ApplicationBar are implemented by the OS. This means if you’re navigating in a loop across pages, your UI can again flicker if the ApplicationBar is being animated to be shown on a page in your loop.

So, here’s a recipe to solve the “Home” navigation challenge. You can see all this code implemented via the BackNavigationHelper class in the accompanying download:

  1. Hide the PhoneApplicationFrame (RootVisual for the app) from the screen while you pop the back stack. This will prevent flickering of the UI (it will flicker once, but you won’t see all your screens go back).
    1. If your pages take too much time, you can show a full-screen Popup with an animation so the user knows what’s happening.
    2. You should also set a flag before a home navigation begins so your pages know not to do a lot of work in their OnNavigatedTo callback. If you’re navigating back, these pages will be unloaded as the navigation is completed (so any UI work they’re doing is thrown away).
  2. Hide the ApplicationBar (by setting its IsVisible property to false) from each page that’s being unwound (if applicable).
    1. Note that this is only required for pages where the ApplicationBar is 100 percent opaque (its Opacity = 1.0).
  3. Unwind the stack.
    1. Call the GoBack method.
    2. Listen for Navigated (on the RootVisual ) and call GoBack again, if you’re not already on the “Home” page.

Reset everything back to normal when you’ve unwound the stack.

Code walkthrough: You can see examples of “take me home” navigation in the pages in the HomeNavigationSamplePages folder in the accompanying code download. The interesting code is, of course, on the BackNavigationHelper class, but our sample has a BackNavConfig page where you can select the options you want to enable in BackNavigationHelper (such as hiding the frame, hiding the application bar, validating journaling and so on).

Page Transitions

The final and most advanced navigation concept you might care about concerns page transitions. In the context of navigation, we think of a transition as the perception of a hand-off between a page that you’re navigating from and the page that you’re navigating to. The navigation is still happening and it’s using the underlying navigation framework we’ve discussed earlier, but as the navigation happens, the content in the PhoneApplicationPages that are participating in the navigation is animated to simulate a hand-off.

The recipe for transitions is a bit more complicated. In fact, just like grandma’s lasagna, there isn’t a single recipe—it will require some “tweaking” to your taste (and application needs). That said, we have a few tenets you should follow, along with a sample and code walkthrough, of course.

The tenets:

  1. Follow all the Back key press principles described earlier. Again, transition is just an extension to navigation—not an excuse to fail certification.
  2. Understand the context and purpose of a transition animation. Windows Phone has a well-defined set of transitions and most of these have a specific context or usage. You must understand the intended usage so you can implement the right transitions in your app. Jeff Arnold (the lead motion designer for Windows Phone) did a brief recording of all the animations and transitions; it’s a must-watch to understand the purpose of each animation. You can find the video at bit.ly/eBTkjD.
  3. Keep your transitions fast and short.
    1. Remember a transition is both an “out” from a page and an “in” on a different page. These two phases will add up. Keep them short. We would say 300 ms total is a good upper limit.
    2. Delay as much UI work as you can during a transition. If your page can avoid data binding or expensive layout operations, consider doing that. You can transition the screen and then quickly move to populating it afterwards.

Figure 1 shows a summary of animations, their usage, directions and relevant notes.

Figure 1 A Summary of Animations

Animation Usage Directions Transition Notes
Turnstile Takes user from one space to another. Defaults across device. It’s heavy by design to emphasize that a transition happened. ForwardIn, ForwardOut, BackwardIn and BackwardOut This will be a common animation you’ll want to use. It’s fairly straightforward.
Continuum Transitions user from one space to another, but gives the perception of continuity. Carries context from one space to the other. Almost feels like you didn’t leave. In, Out Continuum is common, but harder to implement. It requires carrying the continuum context (the perception that a UIElement is carried across two pages).
Swivel Used for transient UI; for example, for dialogs. 
It’s different from other animations in that 
it doesn’t transition, but keeps user in same 
space or at least aims to give that perception. ForwardIn, ForwardOut, FullScreenIn, FullScreenOut, BackwardIn, BackwardOut Not used much for transitions; mostly used for dialogs.
Slide Used for transient UI. Brings content over the existing content. SlideUpFadeIn, SlideUpFadeOut, SlideDownFadeIn, SlideDownFadeOut, SlideLeftFadeIn, SlideLeftFadeOut, SlideRightFadeIn, SlideRightFadeOut Commonly used to transition in transient UIs.
Rotate Rotates the screen in a specific direction 
and angle. In90Clockwise, In90CounterClockwise, In180Clockwise, In180CounterClockwise, Out90Clockwise, Out90CounterClockwise, Out180Clockwise, Out180CounterClockwise Not used much for transitions; mostly used for orientation.

With the three tenets listed earlier in mind, we can now move to coding page transitions. The Windows Phone Controls Toolkit has support for transitions, and it has Storyboards for the most common transitions. 

Note: To follow along with the rest of the article, you’ll need the Silverlight for Windows Phone Toolkit (silverlight.codeplex.com). The code in this article is written against the February release (later releases should work, too).

Toolkit transitions use a TransitionFrame that inherits from PhoneApplicationFrame but has a customized template with two content presenters (where PhoneApplicationFrame has only one content presenter). TransitionFrame listens to changes to its Content property and transitions in the new Content (page) and transitions out the old content. 

Each PhoneApplicationPage determines what transitions it wants using an attached property in the toolkit’s TransitionService class. You can specify up to four transitions for each page, as shown in Figure 2.

Figure 2 The Four Page Transitions that Can Be Specified

Transition (Property Name) Description
NavigationInTransition.Forward Called as you Navigate to this page, with a forward navigation.
NavigationInTransition.Backward Called when the user triggers a back navigation that’s navigating to this page.
NavigationOutTransition.Forward Called as you Navigate away from this page in a forward navigation.
NavigationOutTransition.Backward Called as you Navigate away from this page in a back navigation.

These transitions are instances of an extensible NavigationTransition class. The toolkit includes five built-in NavigationTransitions: TurnstileTranstion, SlideTransition, SwivelTransition, RotateTransition and RollTransition. Again, the system is extensible so you can add your own.

Step-by-step directions to implement transitions using the toolkit are:

1. Download and add a reference to the Silverlight control toolkit.

2. Replace the RootVisual frame for your application by editing the App.xaml.cs and replacing it with a TransitionFrame (see Figure 3).

3. Apply transition properties to your pages (see Figure 4).

Figure 3 Replacing the RootVisual Frame for Your Application by Editing the App.xaml.cs

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 Microsoft.Phone.Controls.TransitionFrame();
    RootFrame.Navigated += CompleteInitializePhoneApplication;

    // Handle navigation failures
    RootFrame.NavigationFailed += RootFrame_NavigationFailed;

    // Ensure we don't initialize again
    phoneApplicationInitialized = true;
  }

Figure 4 Applying Transition Properties to Your Pages

<phone:PhoneApplicationPage 
    x:Class="LWP.TransitionSamples.Turnstile"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True"  xmlns:toolkit=
    "clr-namespace:Microsoft.Phone.Controls;assembly=
    Microsoft.Phone.Controls.Toolkit"
  >

  <toolkit:TransitionService.NavigationInTransition>
    <toolkit:NavigationInTransition>
      <toolkit:NavigationInTransition.Backward>
        <toolkit:TurnstileTransition Mode="BackwardIn"/>
      </toolkit:NavigationInTransition.Backward>
      <toolkit:NavigationInTransition.Forward>
        <toolkit:TurnstileTransition Mode="ForwardIn"/>
      </toolkit:NavigationInTransition.Forward>
    </toolkit:NavigationInTransition>
  </toolkit:TransitionService.NavigationInTransition>
  <toolkit:TransitionService.NavigationOutTransition>
    <toolkit:NavigationOutTransition>
      <toolkit:NavigationOutTransition.Backward>
        <toolkit:TurnstileTransition Mode="BackwardOut"/>
      </toolkit:NavigationOutTransition.Backward>
      <toolkit:NavigationOutTransition.Forward>
        <toolkit:TurnstileTransition Mode="ForwardOut"/>
      </toolkit:NavigationOutTransition.Forward>
    </toolkit:NavigationOutTransition>
  </toolkit:TransitionService.NavigationOutTransition>

Actionable Recipes

To sum up, Windows Phone Silverlight applications have a Web-like navigation model in which you can transition from one page and have a journaling (or history) so you can go back to previous pages. Out-of-the-box, the navigation model is easy to use and relatively complete. There are a few advanced navigation tasks—such as transient UIs, transitions or “jump to home” functionality—that aren’t implemented out of the box, but this two-part article has explained the design considerations you should take into account to implement these more advanced tasks and has given you concise, actionable recipes to implement them.


Yochay Kiriaty is a senior technical evangelist at Microsoft, focusing on client technologies such as Windows and Windows Phone. He coauthored the books “Introducing Windows 7 for Developers” (Microsoft Press, 2009) and “Learning Windows Phone Programming” (O’Reilly Media, 2011).

Jaime Rodriguez is a principal evangelist at Microsoft, driving adoption of emerging client technologies such as Silverlight and Windows Phone. Follow him on Twitter at twitter.com/jaimerodriguez or on blogs.msdn.com/b/jaimer.

Thanks to the following technical expert for reviewing this article: Peter Torr