Search code examples
c#wpfnavigationservice

WPF: Prevent Navigation Service from back navigation


I'm designing an app to update firmware on a device and use the Navigation Service to move freely from page to page. However, I want it such that once you hit the actual firmware update page, you can no longer go back, only forward. If back navigation was allowed we could brick the device, and after it's finished, it doesn't make sense to go back anyhow.

The first attempt was to simply remove the NavigationService.Back() method however this still allows you to go back with the mouse/backspace.

The second attempt was from another SO question using RemoveBackEntry() here. This removed the last entry, however, you could still use the mouse back button and it would take you back 2 pages instead of one (because the last page was removed).

So how do we prevent any sort of back navigation once a page has been reached? It seems like this should be both easy and a common need but I can't find anything on it.

Update: The solution from the answer below indeed works, but with problems. After the firmware update, the next page is a success/fail page, and then the app takes the user back to a main page where they can select a new utility. If a utility is chosen after running another utility to completion, the back navigation is still being blocked for ANY page thereafter.

In fact, what is happening is pressing a back button on another page calls the code from many pages back that prevents us from going back:

if(e.NavigationMode == NavigationMode.Back)
   e.Cancel = true;

My guess is this is because the original page we blocked back navigation on is being kept alive and the PageUnloaded event is never fired. So how can we prevent back navigation on that page and ensure it occurs on only that page?

I'm thinking another potential solution to this would be that once a utility is started, we delete the entire navigation journal. Because once say a firmware update starts, it's completely irrelevant what happened before navigation wise since the user will always be returned to the main page. Would this work?


Solution

  • You can try to use Navigating event for that, something like that

    void NavigationService_Navigating(object sender, NavigatingCancelEventArgs e)
    {
        if (e.NavigationMode == NavigationMode.Back && ...)
        {
            e.Cancel = true;
        }
    }
    

    You can add to the if clause checking the Uri or Content of NavigatingCancelEventArgs to skip navigation to desired page (or use some property from Page/Frame)

    You can also have a look at MSDN to get more details, this article is also helpful