Search code examples
c#uwptemplate10

Navigating back to different page (UWP, Template 10)


I need to ignore a page while navigating back, I tried the following:

public override async Task OnNavigatingFromAsync(NavigatingEventArgs args)
{
    if (args.NavigationMode == NavigationMode.Back)
    {
        args.Cancel = true;
        NavigationService.Navigate(typeof(MainPage));
    } else { 
        args.Cancel = false;
    }
    await Task.CompletedTask;
}

On the page that I am navigating away from, but it seems to only cancel the navigation.

What is the best way to tackle this issue?


Solution

  • In the page that you want to ignore, you can add the following method. This will allow to remove the current page from the navigation history.

    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        // here NavigationService is supposed to be an instance of Template10 INavigationService
        var backStack = NavigationService.FrameFacade.BackStack;
        if (backStack.Count > 0 && backStack.Last().SourcePageType == this.GetType())
        {
            backStack.Remove(backStack.Last());
        }
    
        base.OnNavigatedFrom(e);
    }