.NET MAUI使用Shell导航至MainPage报错的解决求助
MAUI Shell导航至MainPage报错解决方法
问题描述
导航至MainPage时触发异常:
System.Exception:Relative routing to shell is currently not supported. Try prefixing your uri with///:///MainPage
其他视图(如ClassicModeView、ChangeColorModeView)的Shell导航代码可正常运行,仅MainPage导航报错。
核心原因
MainPage是Shell的根ShellContent节点,使用相对路由(直接传入nameof(MainPage))无法定位到根层级页面,必须使用绝对路由格式。
解决方案
方案1:使用绝对路由前缀
修改MainMenuViewModel中的导航命令,在路由前添加///前缀:
[RelayCommand] public async void GoToMenuVM() { await Shell.Current.GoToAsync($"///{nameof(MainPage)}"); }
方案2:移除重复路由注册(可选优化)
由于已在AppShell.xaml中为MainPage设置了Route="MainPage",无需在后台代码重复注册路由,可删除AppShell.xaml.cs中以下代码:
// 移除该行重复注册 Routing.RegisterRoute(nameof(MainPage), typeof(MainPage));
方案3:直接导航至Shell根节点
如果MainPage是Shell的默认根页面,也可以直接用根路由跳转:
[RelayCommand] public async void GoToMenuVM() { await Shell.Current.GoToAsync("///"); }
附用户相关代码
MainMenuViewModel(原报错代码)
[RelayCommand] public async void GoToMenuVM() { await Shell.Current.GoToAsync(nameof(MainPage)); }
AppShell.xaml
<?xml version="1.0" encoding="UTF-8" ?> <Shell x:Class="Clicer_Game.AppShell" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:Clicer_Game.Views" Shell.FlyoutBehavior="Disabled"> <ShellContent Title="Home" ContentTemplate="{DataTemplate local:MainPage}" Route="MainPage"/> </Shell>
AppShell.xaml.cs
public partial class AppShell : Shell { public AppShell() { InitializeComponent(); Routing.RegisterRoute(nameof(ClassicModeView), typeof(ClassicModeView)); Routing.RegisterRoute(nameof(ChangeColorModeView), typeof(ChangeColorModeView)); Routing.RegisterRoute(nameof(MainPage), typeof(MainPage)); // 可移除该行 } }
内容的提问来源于stack exchange,提问作者wojtek
相关产品推荐
相关产品推荐

