MAUI Shell 路由导航通过 GoToAsync 实现,需先注册路由(如 Routing.RegisterRoute("detail", typeof(DetailPage))),支持绝对导航("//detail")、参数传递("detail?id=123")及 QueryProperty 自动绑定,返回用 ".." 而非 PopAsync。

MAUI Shell 中的路由导航主要通过 GoToAsync 方法实现,它基于 Shell 的 URI 路由系统,无需手动管理页面生命周期或导航堆栈,使用起来简洁高效。
在使用 GoToAsync 前,必须先为页面注册路由。通常在 AppShell.xaml.cs 的构造函数中完成:
Routing.RegisterRoute("detail", typeof(DetailPage)); 注册命名路由"detail")是后续跳转的“地址”,不依赖页面路径或类名"products/detail",需确保层级与 Shell 结构匹配(如 TabBar/ShellContent)GoToAsync 是 IAsyncCommand 或页面代码中常用的异步导航方法,调用方式如下:
await Shell.Current.GoToAsync("detail"); —— 跳转到已注册的路由await Shell.Current.GoToAsync("//detail"); —— 使用双斜杠表示绝对导航(清空导航堆栈,类似 Replace)await Shell.Current.GoToAsync("detail?id=123&name=test"); —— 带查询参数,会在目标页的 OnNavigatedTo 中接收被导航的目标页面需继承 ContentPage 并重写 OnNavigatedTo 方法:
ShellNavigationState.QueryString 中QueryProperty 特性自动绑定(更安全、更简洁):[QueryProperty(nameof(ItemId), "id")]
public partial class DetailPage : ContentPage
{
public string ItemId { get; set; }
}框架会在导航时自动解析 URL 中的 id=123 并赋值给 ItemId 属性。
Shell 默认保留导航历史,点击返回按钮即可回退。如需编程式返回:
await Shell.Current.GoToAsync(".."); —— 返回上一级(相对路径)await Shell.Current.GoToAsync("../.."); —— 返回两级// 绝对跳转,再按返回会退出当前 Shell 分支,回到上级结构(如 TabBar)注意:Shell 不支持 PopAsync() 这类传统 NavigationPage 方法,所有操作都应通过 GoToAsync 完成。
基本上就这些。只要路由注册正确、URI 格式规范、参数绑定得当,GoToAsync 就能稳定工作,比手动维护 NavigationStack 更轻量也更符合 Shell 的设计逻辑。
以上就是MAUI Shell怎么实现路由导航 MAUI GoToAsync方法的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号