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

How can I remove the last item in the BackStack in a non-Silverlight app?

假设我有 2 个页面:Page1Page2

当我的应用程序启动时,我导航到 Page1,最终导航到 Page2。在 Page2 上,我想阻止用户使用后退按钮 return 到 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);

None 这就是我想要的。我该怎么做才能完成这项工作?

e.SourcePageType 似乎 return 当前页面的类型 而不是实际来源。我通过添加以下代码解决了这个问题:
对于Page1(由于Page1有时会收到来自App.xaml.csFrame.Navigate()调用,因此会出现ArgumentOutOfRangeException,因为当时没有返回堆栈,所以尝试-需要捕获):

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);

该应用程序现在可以按预期运行。