MAUI Shell导航返回时抛出路由匹配歧义ArgumentException异常
MAUI Shell 返回时出现路由歧义异常的解决方法
问题场景
应用包含HomePage(带ListView)→ DetailsPage → RecordPage的导航流程,从RecordPage点击自动生成的返回按钮时,抛出System.ArgumentException: 'Ambiguous routes matched for: ...'异常,所有页面已完成路由注册。
异常根源
你的代码中**HomePage存在重复路由注册**:
- 在
AppShell.xaml里,通过ShellContent的Route属性给HomePage指定了路由InspectionListPage - 同时在
App.xaml.cs中又通过Routing.RegisterRoute(nameof(HomePage), typeof(HomePage))注册了路由HomePage
这导致Shell处理返回导航时,无法确定匹配哪个路由,引发歧义错误。
解决方案
方案一:保留ShellContent的路由配置,移除代码中的重复注册
- 修改
App.xaml.cs,删除HomePage的路由注册代码:
public partial class App : Application { public App() { InitializeComponent(); MainPage = new AppShell(); Routing.RegisterRoute(nameof(LoginPage), typeof(LoginPage)); // 移除HomePage的重复路由注册 // Routing.RegisterRoute(nameof(HomePage), typeof(HomePage)); Routing.RegisterRoute(nameof(DetailsPage), typeof(DetailsPage)); Routing.RegisterRoute(nameof(RecordPage), typeof(RecordPage)); } }
- 确保所有导航到
HomePage的逻辑都使用InspectionListPage这个路由标识。
方案二:移除ShellContent的Route属性,保留代码中的路由注册
- 修改
AppShell.xaml,删除ShellContent的Route属性:
<Shell xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:MyApp.Mobile.UI;assembly=MyApp.Mobile.UI" Shell.FlyoutBehavior="Disabled"> <ShellContent ContentTemplate="{DataTemplate local:HomePage}" <!-- 移除重复的Route配置 --> /> </Shell>
- 此时
HomePage的路由为nameof(HomePage)即HomePage,和代码中的注册保持一致。
注意事项
- MAUI Shell中,每个页面应只保留唯一的路由标识,避免同时通过XAML属性和代码注册不同路由。
- 导航时使用的路由要和注册的路由完全一致,避免出现不匹配的情况。
内容的提问来源于stack exchange,提问作者Divyesh
相关产品推荐
相关产品推荐

