如何删除Frame.BackStackDepth?

时间:2015-04-10 11:05:07

标签: c# windows-8.1

我正在开发 Windows 8.1 应用,其中包含多个页面。我想知道如何删除 Frame.BackStackDepth ,以便当用户按后退按钮时,应用会转到第一页。 < / p>

我试过了,但它只移除了之前的Frame。

private void backButton_Click(object sender, RoutedEventArgs e)
{
    this.Frame.BackStack.RemoveAt(this.Frame.BackStackDepth-1);
    this.Frame.GoBack();
}

2 个答案:

答案 0 :(得分:1)

您可以使用此扩展方法:

public static void ResetBackStack(this Frame frame)
{
    PageStackEntry mainPage = frame.BackStack.Where(b => b.SourcePageType == typeof(YourPageType)).FirstOrDefault();
    frame.BackStack.Clear();
    if (mainPage != null)
    {
        frame.BackStack.Add(mainPage);
    }
}

只需覆盖NavigationHelper类中的BackPressed事件:使用框架调用该扩展方法,然后导航回来。

或者只是把它放在你的EventHandler中:

private void backButton_Click(object sender, RoutedEventArgs e)
{
    this.Frame.ResetBackStack();
    this.Frame.GoBack();
}

答案 1 :(得分:0)

据我所知,从Windows Phone中,您无法使用命令或方法删除backstack。它并不那么容易。你必须使用循环,直到CanGoBack返回false。这是实现此目的的唯一方法。

我想象你的逻辑,除了第一个打开的页面之外,删除backstack中的所有页面。循环继续异常。

不要忘记定义您的第一个页面名称FirstPage

另请查看msdn链接以获取更多信息。

https://social.msdn.microsoft.com/Forums/windowsapps/en-US/3819f389-3bfc-4c59-a919-272927fc9229/navigation-in-a-metro-application?forum=winappswithcsharp

尝试此解决方案。

do
{
    this.Frame.BackStack.RemoveAt(this.Frame.BackStackDepth - 1);
} while (Frame.CanGoBack && Frame.BackStack.Last(entry => entry.SourcePageType != typeof(FirstPage)) != null);

this.Frame.GoBack();