XAML 为什么在.NET MAUI中调用PopAsync时会出现此异常?

pbpqsu0x  于 2023-04-18  发布在  .NET
关注(0)|答案(1)|浏览(140)

我使用Shell。我在调用AddReviewPage的ViewModel上有以下代码:

private async void OnAddReviewClicked()
    {
        var parameters = new Dictionary<string, object>
        {
            { "ProfessionalId", ProfessionalId }
        };

        await Shell.Current.GoToAsync(nameof(AddReviewPage), parameters);
    }

在AddReviewViewModel中,在数据库上保存信息后,我尝试返回到ProfessionalPage:

private async void OnAddReviewClicked()
    {
        // persistence code 

        if (success == true)
        {
            await App.Current.MainPage.DisplayAlert("Sucess!", "Success!", "OK");

            // This gives me an exception
            await Shell.Current.Navigation.PopAsync();

            // But this code to navigate to the root of the shell works
            // However this isn't the behavior that I want
            //await Shell.Current.GoToAsync("//Main");
        }
    }

我在shell上注册了Professional和AddReview页面:

<Shell
x:Class="MyApp.Presentation.Mobile.AppShell"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyApp.Presentation.Mobile"
xmlns:views="clr-namespace:MyApp.Presentation.Mobile.Views"
Shell.FlyoutBehavior="Disabled">

<ShellContent
    Title="LogIn"
    ContentTemplate="{DataTemplate views:LogInPage}"
    Route="LogInPage" />

<TabBar Route="Main">
    <!-- My main tabs -->
</TabBar>

<ShellContent
    Title="Professional"
    ContentTemplate="{DataTemplate views:ProfessionalPage}"
    Route="ProfessionalPage" />
<ShellContent
    Title="AddReview"
    ContentTemplate="{DataTemplate views:AddReviewPage}"
    Route="AddReviewPage" />

它们也在后面的代码上注册:

public partial class AppShell : Shell
{
public AppShell()
{
    InitializeComponent();

    Routing.RegisterRoute(nameof(LogInPage), typeof(LogInPage));
    Routing.RegisterRoute(nameof(ProfessionalPage), typeof(ProfessionalPage));
    Routing.RegisterRoute(nameof(AddReviewPage), typeof(AddReviewPage));
}
}

但是,当我运行OnAddReviewClicked代码时,我得到了这个异常。

但是导航堆栈不是空的。我是不是做错了路由?

d4so4syb

d4so4syb1#

关于GotoAsync build in back button does not go back to previous page, when working with 3 or more pages也有类似的问题。而且这个bug仍然存在于maui中。
这个问题的原因是您在xaml和AppShell.cs中都注册了页面。所以您可以检查您在AppShell.cs和AppShell.xaml中注册的路由,并使每个页面只注册一次。
此外,您还可以使用register the route of Main in AppShell.xaml, and all other routes in AppShell.xaml.cs

相关问题