简体   繁体   中英

Skip the page in wp7 navigation stack

Let's say I have a code

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    var userInfo = SettingsManager.Read<User>(SettingsManager.UserInfoSetting);

    if (e.NavigationMode == NavigationMode.Back && userInfo == null)
    {
        _mainViewModel.NavigationService.GoBack();
    }

    if (e.NavigationMode == NavigationMode.New && userInfo == null)
    {
        _mainViewModel.NavigationService.NavigateTo(new Uri(ViewModelLocator.SettingPageUrl, UriKind.Relative));
    }

    base.OnNavigatedTo(e);
}

When the user runs application for the first time he will be redirected to the settings page and it works pretty fine right now. If user doesn't want to provide his information he can press back-button in that case I want to skip main page of the application and exit the application. If I run the code I received InvalidOperationException Cannot go back when CanGoBack is false.

The GoBack() method calls PhoneApplicationFrame.GoBack() method to navigate back.

Warning - Removing backstack entries is not recommended by Windows Developer guidelines. Because you have to adhere to the natural behaviour of the back button.

Link - https://docs.microsoft.com/en-us/windows/uwp/layout/navigation-history-and-backwards-navigation

Try removing back stack entries (Main page in your case) when the user goes to the settings page for the first time.

You can remove any remaining backstack entries by the following code:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    while (this.NavigationService.BackStack.Any())
    {
        this.NavigationService.RemoveBackEntry();
    }
}

So when the user presses the back button the application should exit as there are no remaining backstack entries.

You cannot forcibly exit this way.
What you could do, is handle the back button press on the settings page and clear the stack (which is allowed), then let the back button be handled -- thus the user will exit because of the back button, not because of your call.

protected override void OnBackKeyPress(CancelEventArgs e)
    {
        while (NavigationService.CanGoBack)
        {
            NavigationService.RemoveBackEntry();
        }
        base.OnBackKeyPress(e);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM