Search code examples
framewindows-runtimewinrt-xaml

How can I remove pages from a Frame's history?


How can I manipulate a Frame's history in a WinRT XAML app?

The user will start on my hub page, where they can select an existing project to go to its edit screen, or they can select "new project". "New project" will take them through a short wizard, then take them to the "edit project" screen.

It makes sense for the wizard pages to just be pages that I navigate to in the frame; that way the user can back out of the wizard if they change their mind. (It'll only be two pages, so "back" can take the place of "cancel".) But once the wizard is done and the changes are committed, there's no longer any reason for those wizard pages to be in the history; if the user clicks Back from the "edit project" page, I want them to go right back to the hub.

To illustrate, I want the flow to look something like this:

  • Frame history: Hub. User clicks "New Project".
  • Frame history: Hub -> Wizard Page 1. User clicks "Next".
  • Frame history: Hub -> Wizard Page 1 -> Wizard Page 2. User clicks "Finish".
  • Frame history: Hub -> Edit Project.

Frame doesn't seem to have any methods along the lines of "remove from history". The docs do have hints that there might be some way to override the history, because the docs for GoBack say "Navigates to the most recent item in back navigation history, if a Frame manages its own navigation history" (emphasis mine), but that's all it has to say on the topic -- there's no mention of how someone else can manage history for it. So I don't know whether that's useful or not.

How can I remove my wizard pages from my Frame's history once the user completes the wizard?


Solution

  • You can remove pages from the history by calling SetNavigationState(string navigationState) on the frame. Unfortunately the format of the serialized navigationState is "for internal use only", so just changing the string might break your code in future versions.

    I only can think of a future proof method to completely clear the navigation stack:

    1. At program startup save the empty navigation state by calling GetNavigationState.
    2. BEFORE calling Navigate for your Edit Project page, call SetNavigationState with the empty navigation state.

    Your Edit Project page will now be the first page on the stack.