如何在非silverlight应用程序中删除BackStack中的最后一个项目?

本文关键字:BackStack 最后一个 项目 删除 silverlight 应用程序 | 更新日期: 2023-09-27 18:15:46

假设我有两个页面:Page1Page2

当我的应用程序启动时,我导航到Page1,最终导航到Page2。在Page2上,我想防止用户使用后退按钮返回Page1。同样,我想阻止用户使用后退按钮从Page1导航到Page2(从Page2导航到Page1是可能的)。

我知道在Silverlight应用程序中,您只需使用:

NavigationService.RemoveBackEntry();

然而,我的应用程序是使用Windows 10 api构建的,它不是基于silverlight的。我试过:
Page2:

protected override void OnNavigatedTo(NavigationEventArgs e) {
    //...
    if (e.SourcePageType == typeof(Page1)) 
        Frame.BackStack.RemoveAt(Frame.BackStackDepth - 1); // remove the last entry if it represents Page1.
    //...
}

Page1:

protected override void OnNavigatedTo(NavigationEventArgs e) {
    //...
    if (e.SourcePageType == typeof(Page2)) 
        Frame.BackStack.RemoveAt(Frame.BackStackDepth - 1); // remove the last entry if it represents Page2.
    //...
}

我也尝试使用Frame.BackStack.RemoveAt(0);Frame.BackStack.Remove(new PageStackEntry(e.SourcePageType, e.Parameter, e.NavigationTransitionInfo);代替Frame.BackStack.RemoveAt(Frame.BackStackDepth - 1);

这些都不是我想要的。我该怎么做才能让它发挥作用呢?

如何在非silverlight应用程序中删除BackStack中的最后一个项目?

e.SourcePageType似乎返回当前页面的类型,而不是实际的源。我通过添加以下代码解决了这个问题:
对于Page1(由于Page1有时会从App.xaml.cs接收Frame.Navigate()调用,因此ArgumentOutOfRangeException会发生,因为当时没有回栈,因此需要try-catch):

try {
    if (Frame.BackStack[Frame.BackStackDepth - 1].SourcePageType == typeof(Page2))
        Frame.BackStack.RemoveAt(Frame.BackStackDepth - 1);
}
catch (Exception) { // an ArgumentOutOfRangeException }

然后在Page2:

if (Frame.BackStack[Frame.BackStackDepth - 1].SourcePageType == typeof(Page1))
    Frame.BackStack.RemoveAt(Frame.BackStackDepth - 1);

应用程序现在正常运行