Xamarin Forms Shell深层导航返回报错:匹配到模糊路由
问题场景
开发iOS和Android平台的Xamarin Forms应用,仅在AppShell.xaml.cs中通过代码注册全局路由:
// AppShell.xaml.cs Routes.Add(nameof(HousingFolderPage), typeof(HousingFolderPage)); Routes.Add(nameof(HousingFolderDetailsPage), typeof(HousingFolderDetailsPage));
标签栏的MoreServicePage页面点击列表项可正常导航到HousingFolderPage,且一级返回无异常;但从HousingFolderPage导航到HousingFolderDetailsPage后,点击返回按钮抛出路由歧义异常:
[0:] Shell: Failed to Navigate Back: System.ArgumentException: Ambiguous routes matched for: //D_FAULT_TabBar2/IMPL_MoreServicePage/MoreServicePage/HousingFolderPage matches found: //D_FAULT_TabBar2/IMPL_MoreServicePage/MoreServicePage/HousingFolderPage,//D_FAULT_TabBar2/IMPL_MoreServicePage/MoreServicePage/HousingFolderPage
Parameter name: uri
该问题仅出现在二级及以上深度的导航场景。
解决方案
1. 注册唯一路由路径(推荐)
避免直接使用页面类名作为路由,改为指定层级清晰的唯一路由路径,从根源避免歧义:
// AppShell.xaml.cs Routes.Add("HousingFolder", typeof(HousingFolderPage)); Routes.Add("HousingFolder/Details", typeof(HousingFolderDetailsPage));
导航时使用指定的路由名称:
// 从MoreServicePage跳转到HousingFolderPage await Shell.Current.GoToAsync("HousingFolder"); // 从HousingFolderPage跳转到详情页 await Shell.Current.GoToAsync("Details");
2. 启用允许重复路由(临时 workaround)
若需保留原有路由命名,可在导航时添加参数允许重复路由,仅用于临时调试:
await Shell.Current.GoToAsync(nameof(HousingFolderDetailsPage), new ShellNavigationQueryParameters { { nameof(ShellNavigationQueryParameters.AllowDuplicateRoutes), true } });
3. 检查页面XAML的路由配置
确认HousingFolderPage和HousingFolderDetailsPage的XAML中未重复设置Shell.Route属性,避免与代码注册的路由冲突:
<!-- 禁止重复设置此属性 --> <!-- <ContentPage ... Shell.Route="HousingFolderPage"> -->
4. 使用相对导航
在嵌套导航场景中使用相对路径,减少Shell生成重复路由节点的概率:
// 从HousingFolderPage跳转到详情页时指定相对导航 await Shell.Current.GoToAsync(nameof(HousingFolderDetailsPage), relative: true);
内容的提问来源于stack exchange,提问作者Nabil Akhlaque

