根页面不属于 Navigation.NavigationStack 集合

Root Page is not part of the Navigation.NavigationStack collection

当我的应用程序启动时,我在 AppDelegate 中添加了一些逻辑,并根据该逻辑的结果为 MainPage 分配了一个页面。

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    global::Xamarin.Forms.Forms.Init ();

    // .....

    if(authorizationStatus == PhotoLibraryAuthorizationStatus.Authorized)
    {
        bokehApp.SetStartupView(serviceLocator.GetService<AlbumsPage>());
    }
    else
    {
        bokehApp.SetStartupView(serviceLocator.GetService<StartupPage>());
    }
}

在我的 app.cs 中,我从 AppDelegate

分配给定视图 MainPage
public class App : Xamarin.Forms.Application
{
    public void SetStartupView(ContentPage page)
    {
        this.MainPage = new NavigationPage(page);
    }
}

在这种情况下,我将 StartupPage 传递给 SetStartupView(Page) 方法。当用户做某事时,我导航到 AlbumsPage.

this.Navigation.PushAsync(new AlbumPage());

当我这样做时,AlbumPage 被创建并导航到;它的 Navigation.NavigationStack 集合只包含它自己,而不是它刚刚导航的页面。我想要做的是阻止对 this.Navigation.PopAsync() 的调用导航回 StartupPage,这就是当前发生的情况。

最初我只是 运行 一个循环并弹出原始页面,然后删除所有剩余的页面,在本例中为 StartupPage

// Grab the current page, as it is about to become our new Root.
var navigatedPages = this.Navigation.NavigationStack.ToList();
Page newRootPage = navigatedPages.Last();

// Dont include the current item on the stack in the removal.
navigatedPages.Remove(newRootPage);

while(navigatedPages.Count > 0)
{
    Page currentPage = navigatedPages.Last();
    this.Navigation.RemovePage(currentPage);
}

但是,当我查看时,Navigation.NavigationStack 集合 包含 AlbumsPage。然而,调用 this.Navigation.PopAsync() 导航回 StartupPage.

我需要做什么才能重置此导航堆栈,以便弹出不会导航回初始页面?

更新

当我导航时,我已经能够使用这个:

App.Current.MainPage = new NavigationPage(viewModelPage);

如@Daniel 所建议,但这会阻止动画发生。我也试过

await App.Current.MainPage.Navigation.PushAsync(fooPage);
App.Current.MainPage = new NavigationPage(fooPage);

当我这样做时,我看到新页面转换到,但是一旦 PushAsync 上的 await 调用完成,并且 MainPage 被替换,页面就会消失,我只剩下一个空白的屏幕。

我真的不想在从我的设置页面过渡到实际应用程序的过程中丢失动画。

我想你要找的是设置:

App.Current.MainPage

到一个新的NavigationPage。它取代了应用程序的主页。

我能够解决问题。这主要是因为我不了解 NavigationPage 的工作原理。似乎每个页面都有自己的导航堆栈。当我在页面之间导航并检查它们的 NavigationStack collections 时,它们总是只有一个项目。

然后我开始查看 App.Current.MainPage.Navigation 并发现它实际上拥有整个堆栈(StartupPageFooPage)。然后我能够在将 FooPage 推送到导航堆栈之前获取 StartupPage,然后在导航到 FooPage 完成后删除 StartupPage。这基本上让我重置根页面,同时保持视图之间的过渡动​​画。

Page originalRootPage = App.Current.MainPage.Navigation.NavigationStack.Last();
await App.Current.MainPage.Navigation.PushAsync(new FooPage());
App.Current.MainPage.Navigation.RemovePage(originalRootPage);

当 time-period 过期并且我被允许时,我会将其标记为已回答。

这解决了我的问题。

    protected override bool OnBackButtonPressed()
    {
        foreach (Page page in Navigation.ModalStack)
        {
            page.Navigation.PopModalAsync();
        }

        return true;
    }