سؤال

I have a phone page which navigates to another. Is there a way to prevent the fist page from getting into the backstack when navigating to the second?

I'd rather not remove the first page from the backstack in the code for the second page.

هل كانت مفيدة؟

المحلول

The most obvious way kind of works:

NavigationService.Navigate(new Uri(...));
NavigationService.RemoveBackEntry();

But it may fail - see submision problems described here.

If you were to remove the BackStack Entry on the second page (and thus disperse the knowledge of the first page behaviour in context of navigation), you would to that in OnNavigatedTo, which occurs after the navigation is completed and the entry is placed on the BackStack. PhoneApplicationPage similarly has OnNavigatedFrom method, which is also called after the navigation is completed (OnNavigatingFrom is called before navigation and allows cancelling). So first page could remove itself in the following way:

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    NavigationService.RemoveBackEntry();
}

However, this method is incomplete, as OnNavigatedFrom is called not only after a succesfull Navigate, but also after pressing any of the three device buttons or showing a Launcher or Chooser (from Microsoft.Phone.Task). In those cases current page will not be placed on the BackStack (I guess that's why the BackStack corrections are applied usually on other Pages). So to fix the above method you could check if the last entry is what it should be:

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
    var entry = NavigationService.BackStack.FirstOrDefault();
    if (entry != null && entry.Source.OriginalString.Contains(...))
    {
        NavigationService.RemoveBackEntry();
    }
}

نصائح أخرى

I have the same requirement when implementing a login page. Upon navigation to the authenticated area of the app, I want to remove the login page from the backstack.

To do this, I simply pop the stack after the call for the navigation out of the login view.

NavigationService.Navigate("/Page2.xaml");
NavigationService.RemoveBackEntry();

This doesn't require code in your Page2.xaml.

No, there is no way. Why won't you remove it if you don't want it to be there?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top