arrow-left arrow-right brightness-2 chevron-left chevron-right circle-half-full dots-horizontal facebook-box facebook loader magnify menu-down RSS star Twitter twitter GitHub white-balance-sunny window-close
WPF Navigation
15 min read

WPF Navigation

This is an old post and doesn't necessarily reflect my current thinking on a topic, and some links or images may not work. The text is preserved here for posterity.

In 2001, Microsoft published a paper called Inductive User Interface Guidelines. If you have not read this paper, I would suggest doing so. It is largely technology agnostic, and I know that many of my colleagues at Readify consider it to be a classic. In this article I want to look at building inductive user interfaces with WPF.

PS: If you are interested in building WPF Navigation applications, check out Magellan.

Navigation Applications

Navigation applications are applications that are composed of many "pages", and often feel similar to web applications, although not always. A navigation application usually provides some kind of shell in which the pages are hosted, with custom chrome or widgets around it.

The pages of a navigation application can usually be broken down into two categories:

  1. Standalone, free pages.
  2. Pages that make up a step in a process.

For example, an online banking application may have a number of standalone pages, such as:

  • The Welcome page
  • The Account Balance page
  • The Help page

These pages are often read-only, or can be navigated to at any time, and don't really form part of a single "task" that the user performs.

Then there are many tasks the user can perform:

  • Applying for a credit card
  • Paying a bill
  • Requesting to increase their transaction limits

Note that these tasks may comprise of subtasks, which can make our navigation model rather complex. Let's dissect each of these sections and discuss how WPF handles them.

The Shell

The Shell is usually the main window of your application, and it's where your pages are hosted. In WPF, you have two options:

  1. If you are building a XAML Browser Application, or XBAP, the shell will normally be the web browser that is hosting your application. It is possible to create your own shell within the browser window, though it may confuse users.
  2. If you are building a standalone application, you will need to build your own shell.

Building your own shell is as simple as creating a standard WPF Window in a normal WPF application, and using a WPF Frame element. The Frame's job is to declare a section of the window that your pages will be hosted in, and to provide all of the services around navigation. Here is an example:

<Window 
    x:Class="NavigationSample.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300"
    >
    <DockPanel>
        <Frame x:Name="_mainFrame" />
    </DockPanel>
</Window>

From code, you can tell the frame to navigate, like so:

_mainFrame.Navigate(new Page1());

Which just so happens to be a helpful shortcut to:

_mainFrame.NavigationService.Navigate(new Page1());

NavigationService

Navigation comprises many functions: going back, going forward, going to a new page, refreshing a page, and so on. Objects in the WPF Navigation ecosystem, like the Frame class, as well as the Page class which I'll describe shortly, can access this functionality by a NavigationService property, which is, surprisingly of type NavigationService. For example:

_mainFrame.NavigationService.GoBack(); 
_mainFrame.NavigationService.GoForward(); 
_mainFrame.NavigationService.Refresh();

This same object is made available to every page hosted within the frame, so pages can signal that they wish to navigate backwards or forwards. When navigating, the Navigate method will accept just about anything you want:

_mainFrame.NavigationService.Navigate(new Uri("http://www.google.com/"));
_mainFrame.NavigationService.Navigate(new Uri("Page1.xaml", UriKind.Relative));
_mainFrame.NavigationService.Navigate(new Page1());
_mainFrame.NavigationService.Navigate(new Button());
_mainFrame.NavigationService.Navigate("Hello world");

In the first case, it will load a full web browser control with Google within the frame. In the second case, it will resolve a WPF page by looking up the XAML Uri in the application's resources and display the page. In the third case, it will show the same XAML page from a direct object reference. In the fourth, it will display a Button object direct to the screen, without a page around it. And in the last case, it will show a string enclosed within a TextBlock. Frames can show just about anything.

Frames make their content public through the Content dependency property, which makes it easy to bind to. When navigating to a page, for instance, the Content property will give you a Page object. Showing the title of the current page in your shell becomes very trivial:

<Window 
    x:Class="NavigationSample.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    <strong>Title="{Binding Path=Content.Title, ElementName=_mainFrame}"</strong>
    Height="300" Width="300"
    >    
    <DockPanel>
        <Frame x:Name="_mainFrame" />
    </DockPanel>
</Window>

The NavigationService also provides a number of events you can subscribe to, if you want to control the navigation process:

  • Navigating, when the frame is about to navigate. Set Cancel to true to stop.
  • Navigated, when navigation has finished but before it is rendered
  • NavigationFailed, when something goes wrong
  • NavigationProgress, when chunks of a remote navigation call are being downloaded. Nice for progress bars.
  • NavigationStopped, when the StopLoading method is called (like clicking "Stop" in IE) or a new Navigate request is made during downloading
  • LoadCompleted, when the page has been rendered

Customizing the Chrome

The Frame control ships with a standard UI that provides back and forward buttons once you have navigated to a second page. Out of the box, it looks very similar to IE 7.0, although it doesn't take into account your current Windows theme:

A WPF frame with the standard chrome

Fortunately, just like every other WPF control, how the frame looks is completely up to you. Just apply a ControlTemplate and use a ContentPresenter to show the content of the page:

<ControlTemplate TargetType="Frame">
    <DockPanel Margin="7">
        <StackPanel 
            Margin="7"
            Orientation="Horizontal"
            DockPanel.Dock="Top"
            >
            <Button 
                Content="Avast! Go back!" 
                Command="{x:Static NavigationCommands.BrowseBack}" 
                IsEnabled="{TemplateBinding CanGoBack}" 
                />
            <Button 
                Content="Forward you dogs!" 
                Command="{x:Static NavigationCommands.BrowseForward}" 
                IsEnabled="{TemplateBinding CanGoForward}" 
                />
        </StackPanel>

        <Border 
            BorderBrush="Green"
            Margin="7"
            BorderThickness="7"
            Padding="7"
            CornerRadius="7"
            Background="White"
            >
            <ContentPresenter />
        </Border>
    </DockPanel>
</ControlTemplate>

WPF Frame with a custom ControlTemplate

In that example, TemplateBindings are used because the Frame (being templated) exposes CanGoBack and CanGoForward properties. The NavigationCommands are a set of static routed UI commands that the frame will automatically intercept - there's no need for C# event handlers to call NavigationService.GoBack().

The NavigationService and Frame object expose many other properties and events; these are just the tip of the iceberg, and the ones you'll customize most often when building inductive UI's with WPF.

Note: WPF includes a class called NavigationWindow, which is essentially a Window which also doubles as a Frame, by implementing most of the same interfaces. It sounds useful at first, but most of the time you need more control over the Window, so I've never had any need to use this class. I am just pointing it out for the sake of completeness, though your mileage may vary.

Pages

Pages are the cornerstone of navigation applications, and are the primary surface users interact with. Similar to Windows or UserControls, a Page is a XAML markup file with code behind. If you are working with XBAP's, the Page is the root of the application.

Just like a Window or UserControl, a page can only have one child, which you'll need to set to a layout panel to do anything fancy. You can do whatever you like in a WPF Page - 3D, animation, rotation; it's just like any other control.

Using the Navigation Service from a Page

Each Page has a reference to the NavigationService object provided by its container - usually a Frame. Note that the Page and its containing Frame will share the same reference to the NavigationService, so the Page won't be able to reference it during it's constructor.

The Page can make use of the NavigationService's Navigating event to stop users navigating away from the page, by setting the Cancel property on the event arguments. This is useful if the user has unsaved changes on the page, and you want to give them a chance to save them. Don't worry about unsubscribing from the event either - WPF will detect when you navigate away from the page, and automatically removes all event handlers, to avoid any memory leaks (since the NavigationService object lives a lot longer than any particular page would).

Since the page is hosted within the Frame in the Visual Tree, you can also make use of some of the NavigationCommands routed commands, since the parent Frame will automatically handle them:

<Page 
    x:Class="NavigationSample.Page2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Page2"
    >
    <Grid>
        <Button Command="{x:Static NavigationCommands.BrowseBack}">Cancel</Button>
    </Grid>
</Page>

In addition, you can of course use the NavigationService to perform any other kind of navigation, such as navigating to a new page or going backwards.

Hyperlinks

One additional feature you can use when building pages is the Hyperlink control, and the automatic navigation it provides. Hyperlink is an Inline, so it has to be used within a control like a TextBlock or FlowDocument paragraph. You can use it in other WPF applications, but automatic navigation only works within navigation applications. Here is an example:

<Page 
    x:Class="NavigationSample.Page1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Page1"
    >
    <Grid>
        <TextBlock>
            <Hyperlink NavigateUri="Page2.xaml">Go to page 2</Hyperlink>
        </TextBlock>
    </Grid>
</Page>

Passing data between pages

There are two ways you can pass information between pages using WPF. First, I'll show you the way *not *to do it, then I'll show the preferred way to do it :)

Although it's not obvious, you can pass query string data to a page, and extract it from the path. For example, your hyperlink could pass a value in the URI:

<TextBlock>
    <Hyperlink NavigateUri="Page2.xaml?Message=Hello">Go to page 2</Hyperlink>
</TextBlock>

When the page is loaded, it can extract the parameters via NavigationService.CurrentSource, which returns a Uri object. It can then examine the Uri to pull apart the values. However, I strongly recommend against this approach except in the most dire of circumstances.

A much better approach involves using the overload for NavigationService.Navigate that takes an object for the parameter. You can initialize the object yourself, for example:

Customer selectedCustomer = (Customer)listBox.SelectedItem;
this.NavigationService.Navigate(new CustomerDetailsPage(selectedCustomer));

This assumes the page constructor receives a Customer object as a parameter. This allows you to pass much richer information between pages, and without having to parse strings.

Page Lifecycles

Many people have been confused about how long pages live for and how Back/Forward navigation works. The simplest way to demonstrate this is to create a couple of simple pages, Page1 and Page2, which contain hyperlinks to each other. I am going to write the same tracing code in each page:

public Page1()
{
    InitializeComponent();
    Trace.WriteLine("Page 1 constructed");
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    Trace.WriteLine("Page 1 navigating to page 2");
    this.NavigationService.Navigate(new Uri("Page2.xaml", UriKind.Relative));
}

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    Trace.WriteLine("Page 1 loaded");
}

private void Page_Unloaded(object sender, RoutedEventArgs e)
{
    Trace.WriteLine("Page 1 unloaded");
}

~Page1()
{
    Trace.WriteLine("Page 1 destroyed");
}

I've also handled the Back and Forward buttons myself, so I can trace when they are clicked, and I've added a button to force the garbage collector to run. Here's what happens:

Page 1 navigating to page 2
Page 2 constructed
Page 1 unloaded
Page 2 loaded
Garbage collector runs
Page 1 destroyed
Clicked Back
Page 1 constructed
Page 2 unloaded
Page 1 loaded
Garbage collector runs
Page 2 destroyed

So, the navigation system works as you expect - the page is unloaded, and available for the garbage collector. However, it does become more complicated. Suppose your page required some kind of parameter data to be passed to it:

public Page1(DateTime date)
{
    InitializeComponent();
    Trace.WriteLine("Page 1 constructed " + date.ToString());
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    Trace.WriteLine("Page 1 navigating to page 2");
    this.NavigationService.Navigate(new Page2(DateTime.Now));
}

When navigating, if you click "Back", WPF can't possibly know what values to pass to the constructor; therefore it must keep the page alive. Here's the trace output:

Page 1 navigating to page 2
Page 2 constructed 5/06/2008 12:23:19 PM
Page 1 unloaded
Page 2 loaded
Garbage collector runs
Clicked Back
Page 2 unloaded
Page 1 loaded

Notice that although the pages are loaded and unloaded many times, it is the same page instance. This means that:

  • If you navigate using a URI, WPF will create the page by invoking the constructor each time. The navigation history keeps the URI, not the object.
  • If you navigate passing an object directly, WPF will keep the object alive.

This gives you a few things to consider:

  • Over time, that can amount to some serious memory usage.
  • The Loaded and Unloaded events are called each time the page is shown or disappears, so use them as chances to clear all the data you can in order to minimize memory.
  • The URI navigation mode explained above *can *be useful for these reasons, but don't abuse it :)

Lastly, each page provides a KeepAlive boolean property, which is false by default. However, it only applies when using URI navigation, which explains why many people have tried changing it only to see no difference. Back/forward simply couldn't work if objects were not kept alive, since the navigation service has no way to construct them. An option I'd like to see is being able to pass a lambda or delegate which is used to reload the page.

PageFunctions

WPF Pages serve to allow us to build standalone pages within our application - pages like Welcome, Help, or View Account Balances. However, when it comes to completing tasks, they fall short in a number of ways. Consider the scenario for paying a bill:

A simple navigation workflow

Once the task is complete, you need to return to the Home page. Should the Confirm page be written to Navigate directly to the Home page when a button is clicked? What if the Pay Bill task was triggered from another page? And if the user clicks "Back" upon arriving back at the Home page, should they get to cancel the payment after they already confirmed it? And what if we don't want to allow them to go back?

Now consider a more sophisticated example. Maybe the biller they want to pay doesn't appear in their list of existing billers. You might have another task to define a biller - something like this:

Workflow with a sub-workflow

This causes us to think carefully about our navigation model:

  • Will the Verify and Confirm page be hard-coded to transition to Transaction details?
  • When they get to the Transaction Details page, what will clicking "Back" in the shell do?
    • If it went to Verify and Confirm, we'd be in trouble, since the biller has already been saved

What we are really doing here is interrupting one task to start another - like taking a detour - and then returning to our previous task. After we return, we can then complete the original task. Once a task returns, its navigation journal should be cleared, and it should be as if the detour never happened. This creates a couple of rules:

  • Within a task, you can click back or forward as much as you like, until it returns.
  • When a task is completed, the browser history "stack" is unwound to where it was when the task began

It's helpful to picture this as code:

PaidBill PayBill()
{
    var biller = SelectBiller();
    EnterTransactionDetails(biller);
    return Confirm();
}
Biller SelectBiller()
{
    if (BillerAlreadyExists)
        return SelectExisting();
    else
        return CreateNew();
}

Where each function represents a task that can branch out, and then return to the original task.

Introducing PageFunctions

Now you can begin to sense where Page Functions get their name. WPF Page Functions are a special type of Page that inherit from a PageFunction<T> class. They are standard Page objects, but with one difference: they provide a Return event which makes it possible to unwind the navigation journal.

Returning

Just like our pseudo code above, and like any other kind of function, when a PageFunction returns it needs to declare a type of object that is being returned, so that the page which triggered the PageFunction can get data back from it. Here's what a the code behind might look like:

public partial class VerifyAndConfirmNewBillerPage : PageFunction<Biller>
{
    public VerifyAndConfirmNewBillerPage(Biller newBiller)
    {
        InitializeComponent();
        this.DataContext = newBiller;
    }

    private void ConfirmButton_Click(object sender, RoutedEventArgs e)
    {
        this.OnReturn(new ReturnEventArgs<Biller>((Biller)this.DataContext));
    }
}

Notice that the class inherits from a generic type. When the user clicks "confirm" on this page, it will raise a Return event to whatever page instantiated it, and returns the Biller that was created.

The page that came before this one would need to subscribe to the event in order to expect it. Here is how that would look:

public partial class DefineNewBillerPage : PageFunction<Biller>
{
    public DefineNewBillerPage()
    {
        InitializeComponent();
        this.DataContext = new Biller();
    }

    private void SubmitButton_Click(object sender, RoutedEventArgs e)
    {
        var nextPage = new VerifyAndConfirmNewBillerPage((Biller)this.DataContext);
        nextPage.Return += new ReturnEventHandler<Biller>(BillerVerified);
        this.NavigationService.Navigate(nextPage);
    }

    private void BillerVerified(object sender, ReturnEventArgs<Biller> e) 
    {
        this.OnReturn(e);
    }
}

When the user enters information about their new biller and click "Submit", we navigate to the Verify and Confirm page, and we subscribe to its Return event. On that page, they'll hit Confirm, which will Return control back to our page. Our page will then also return - this is similar to when you make a function call at the last line of an existing function, in that the innermost function's stack is cleared, it returns to the calling function, and then that function returns.

Back at the Select Existing Biller page, here's how that code behind would appear:

public partial class SelectExistingBillerPage : PageFunction<PaidBill>
{
    public SelectExisingBillerPage()
    {
        InitializeComponent();
        this.DataContext = GetAllExisingBillers();
    }

    private void AddNewButton_Click(object sender, RoutedEventArgs e)
    {
        var nextPage = new DefineNewBillerPage();
        nextPage.Return += new ReturnEventHandler<Biller>(NewBillerAdded);
        this.NavigationService.Navigate(nextPage);
    }

    private void NewBillerAdded(object sender, ReturnEventArgs<Biller> e) 
    {
        // A biller has been added - we can pluck it from the event args
        var nextPage = new EnterTransactionDetailsPage(e.Result);
        this.NavigationService.Navigate(nextPage);
    }

    private void SelectExisingButton_Click(object sender, RoutedEventArgs e)
    {
        var nextPage = new EnterTransactionDetailsPage((Biller)listBox1.SelectedItem);
        this.NavigationService.Navigate(nextPage);
    }
}

Note how in the return event handler our page navigates to the Transaction Details page? Thus, our navigation is actually:

Workflow with a sub-workflow using Return events

This model allows pages to complete a task, return to whoever called them, and have the previous task continue without any additional knowledge. To users, it would appear as a detour, where in reality the pages operate just like function calls.

Since one page returns to the caller, it might be worrying that the previous page will quickly flash up before navigating. Fortunately, this is not the case, as WPF waits for the Return event handler to execute before loading or rendering the previous page. If the Return event handler from the calling page asks to navigate somewhere else, WPF would perform the navigation without showing the page.

Markup

PageFunctions do inherit from the Page base class, and apart from the concept of returning, they operate just like any other Page. Since the base class is generic, the XAML accompanying the PageFunction does look slight different:

<PageFunction
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:<strong>domain</strong>="clr-namespace:DomainModel" 
    x:Class="NavigationSample.DefineNewBillerPage"
    <strong>x:TypeArguments="domain:Biller"</strong>
    Title="Define a new Biller"
    >
    <Grid>
        <... />
    </Grid>
</PageFunction>

PageFunction Lifecycles

When using PageFunctions, you need a reference to the object in order to subscribe to the event and for the handler to be invoked, and so navigation with PageFunctions always involves the PageFunction object being left alive in memory; similar to normal pages. Thus, KeepAlive generally has no effect on PageFunctions.

Fortunately, once a PageFunction has returned, it is removed from the navigation journal and can be garbage collected. This means that although the pages that make up a task will consume memory, once the task is finished, the pages are destroyed. In this way, a largely task-focused UI can use the rich navigation model without degrading performance.

Summary

Navigation applications are made up of many pages, which can be categorized as either standalone pages, or pages that contribute towards a step in a user's task. Standalone pages are usually represented as Page objects, and steps within a task are represented as PageFunctions. Pages of any kind can be hosted with a WPF Window using the Frame control, or within an XBAP application hosted by the browser.

The NavigationService object shared between a Page and it's host provides many hooks into the navigation system. Page lifecycles can complicate things, but are logical when you think about them. Pay special attention to the lifetime of your pages and find ways to reduce their memory footprint when not in view (remove all data during the Unloaded event, and restore it during the Loaded event, for example). As always, use memory profilers to detect major leaks.

Navigation applications make it easy to build user interfaces that are task-focused and geared for ease-of-use over productivity. This style of UI is very difficult to achieve using Windows Forms or other UI systems. Even on the web, which shares similar navigation styles, concepts such as journal unwinding, returning to calling pages and remembering state between pages can be notoriously difficult to implement. Entire frameworks in like Struts in Java exist to enable just these scenarios.

Paul Stovell's Blog

Hello, I'm Paul Stovell

I'm a Brisbane-based software developer, and founder of Octopus Deploy, a DevOps automation software company. This is my personal blog where I write about my journey with Octopus and software development.

I write new blog posts about once a month. Subscribe and I'll send you an email when I publish something new.

Subscribe

Comments