如何清除 Xamarin/MAUI 中的导航?

Tho*_*ton 3 xamarin maui

我有以下应用程序结构:

Main Page : Choose Login Type A or B

if the user choses login type A then navigate to > Page A1 Credentials for A type
if the user choses login type B then navigate to > Page B1 Credentials for B type

if Login is successful for page A1 navigate to > Page A2
if Login is successful for page B1 navigate to > Page B2


            Page A1 --- Login Successful ---> Page A2
          /
         /
        /
Page 1  \
         \
          \
            Page B1 --- Login Successful ---> Page B2
Run Code Online (Sandbox Code Playgroud)

如果用户在页面 A1 或 B1,我希望他可以根据需要返回到页面 1。但是,如果用户使用类型 1 或 2 登录并到达 A2 或 B2,则不应允许他返回。

这是我的代码:

在转到 A2 或 B2 页面之前,我会运行。(此代码在页面A1、B1中执行):

public static void RemoveAllPagesFromNavigation(INavigation Navigation)
    {
        var existingPages = Navigation.NavigationStack.ToList();
        foreach (var page in existingPages)
        {
            if (page != null)
            {
                Navigation.RemovePage(page);
            }
        }
    }

RemoveAllPagesFromNavigation(this.Navigation);
await Navigation.PushAsync(new PageA2());       // Or PageB2
Run Code Online (Sandbox Code Playgroud)

但是函数RemoveAllPagesFromNavigation会引发异常,指出NavigationStack 的第一个元素为null;

我添加了一个条件来跳过第一页为空的情况,该函数运行但最终用户仍然能够返回到页面第 1 页。

如何防止用户返回页面 1、A1 或 B2?

Too*_*eve 6

根据Shell 导航 / 绝对路线//,在路线开头使用将会替换当前的导航堆栈。这样就无处可退了。

await Shell.Current.GoToAsync("//Page2");
Run Code Online (Sandbox Code Playgroud)

仅供参考替代方案:

有另一种导航范例,NavigationPage,它缺少诸如“路线”之类的 appshell 功能。优点是对导航堆栈进行简单、直接、编程的控制。(没有 AppShell 引入的微妙之处。您已经遇到过其中之一。)

考虑在登录序列期间使用NavigationPage,仅在用户进入主要内容时才转到 AppShell。(或者完全省略 AppShell,只需为您的应用程序使用 NavigationPage。)

为此,请在 App.xaml.cs 中,将: 替换
MainPage = new AppShell();
为:
MainPage = new NavigationPage();

然后使用NavigationPage功能显示第一个登录页面等。不要使用我之前链接的 AppShell 导航文档中的任何内容。

如果登录成功后,您想使用AppShell导航,请执行:
Application.Current.MainPage = new AppShell();


第三种选择:

执行Application.Current.MainPage = new MyNextFascinatingPage();登录序列。因此,在这些步骤中,用户无处可返回。(如果您希望他们返回,您可以通过创建new早期页面的副本来明确地执行此操作。)

登录成功后,执行:
Application.Current.MainPage = new AppShell();