Search code examples
c#wpfnavigationnavigationservice

WPF NavigationService "RemoveBackEntry" is removing the oldest entry, rather than the most recent


I have a fairly simple WPF application with a handful of pages. Upon submit of a form, I'm wanting to navigate to a specific page, then clear out the last navigation entry so that the user is unable to then resubmit that form they had just submitted.

However, when I call "RemoveBackEntry()" on the navigation service after navigating to the specific page, it removes the 3rd entry (which is the oldest in this case) in the back stack rather than the page I'm navigating from. That page remains as the most recent entry in the back stack when the new page loads.

Here's my code, although it's quite simple and straight forward.

  public void NavigateToNewWorkPage()
    {
        _view.NavigationService?.Navigate(new WorkPage());
        _view.NavigationService?.RemoveBackEntry();
    }

Solution

  • I had the same problem and solved it by using the events the NavigationService provides.

    The NavigationService.Navigate(..) method is async and when you call RemoveBackEntry() your current view is not yet in the back entries journal. So you remove the view which was the last back entry before navigating. You could solve it like this:

    public void NavigateToNewWorkPage()
    {
        if (_view.NavigationService != null)
        {
            _view.NavigationService.Navigated += NavServiceOnNavigated;
            _view.NavigationService.Navigate(new WorkPage());
        }
    }
    
    private void NavServiceOnNavigated(object sender, NavigationEventArgs args)
    {
        _view.NavigationService.RemoveBackEntry();
        _view.NavigationService.Navigated -= NavServiceOnNavigated;
    }
    

    You wait for the Navigated event so the view you navigate from became the last back entry and then you remove it.