MAUI Shell导航.短暂显示错误页面



我正在使用非常基本的Shell导航创建一个基本的MAUI应用程序(仅限Android)。有没有人能确认(或不确认)以下方法是否有效?它可以工作,但在导航时,偶尔会在找到正确的页面之前短暂地显示错误的页面。

我不需要弹出或选项卡菜单。MauiProgram.cs中的所有页面都作为singleton添加。例如

builder.Services.AddSingleton<MainPage>();

所有页面都有在AppShell.xaml.cs中注册的路由。例如

Routing.RegisterRoute(nameof(MainPage), typeof(MainPage));

在ViewModel中,所有的页面都有使用[RelayCommand]打开其他页面的按钮。例如

await Shell.Current.GoToAsync(nameof(Page1), false);

AppShell.xaml中路由结构平坦:

<?xml version="1.0" encoding="UTF-8" ?>
<Shell
x:Class="MyMauiApp.AppShell"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyMauiApp.Views"
Shell.FlyoutBehavior="Disabled">
<ShellContent
Title="MainPage"
ContentTemplate="{DataTemplate local:MainPage}"
Route="MainPage" />
<ShellContent
Title="Page1"
ContentTemplate="{DataTemplate local:Page1}"
Route="Page1" />
<ShellContent
Title="Page2"
ContentTemplate="{DataTemplate local:Page2}"
Route="Page2" />

等等……

MainPage转到Page1,
Page1转到Page2(或返回到MainPage),
Page2转到Page3(或返回到Page1),
Page3转到Page4(或返回到Page1)等等。

它可能不会按顺序向前和向后浏览所有页面(我希望能够从任何其他页面转到任何页面)。这是有效的,但特别是当返回时(在后面的代码中使用受保护的覆盖bool OnBackButtonPressed()),一个不同的页面被简要显示。例如在page3page . example .cs

protected override bool OnBackButtonPressed()
{
page3PageViewModel.PageGoBack();
return true;
}

和在page3PageViewModel.cs

public async void PageGoBack()
{
await Shell.Current.GoToAsync("//" + nameof(Page1), false); 
}

结果是正确的,但它看起来很乱。建议欢迎。

答案是不要在AppShell中包含路由。Xaml(可视层次结构)并在后面的代码中注册相同的路由。只需要在AppShell的可视化层次结构中包含MainPage。xaml,例如:

<?xml version="1.0" encoding="UTF-8" ?>
<Shell
x:Class="MyMauiApp.AppShell"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyMauiApp.Views"
Shell.FlyoutBehavior="Disabled">
<ShellContent
Title="MyMauiApp"
ContentTemplate="{DataTemplate local:MainPage}"
Route="MainPage" />
</Shell>

其他页面类似于详细页面,它们的路由可以在AppShell.xaml.cs中注册,如下所示:

名称空间MyMauiApp;

public partial class AppShell : Shell
{
public AppShell()
{
InitializeComponent();
Routing.RegisterRoute(nameof(Page1), typeof(Page1));
Routing.RegisterRoute(nameof(Page2), typeof(Page2));
Routing.RegisterRoute(nameof(Page3), typeof(Page3));
}
}

正如文档所说(我错过了):

的附加路由可以显式地注册到任何没有在Shell可视化层次结构中表示的详细页面。这是通过Routing完成的。RegisterRoute方法'

"这些详细页面可以在应用程序的任何地方使用基于uri的导航导航。这些页面的路由被称为全局路由。">

这些页面可以通过名称直接导航到。如。等待Shell.Current.GoToAsync("Page1";

相关内容

最新更新