You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MAUI Shell动态添加层级路由失败,能否编程实现?

MAUI Shell动态添加层级路由的正确方式

MAUI Shell支持通过编程方式添加层级路由,但直接给ShellContent设置带斜杠的Route是错误的——Shell的层级路由依赖于ShellItem → ShellSection → ShellContent的层级结构,斜杠对应容器节点的路由段,而非单个ShellContent的路由属性。

错误原因

你之前直接在ShellContent.Route中写{SystemConnection.Name}/{ServerName},Shell会把整个字符串当作单个路由段,无法识别层级关系,因此导航时找不到匹配的路由。

正确实现步骤

  1. 创建/获取父级路由容器:先检查是否存在对应SystemConnection.Name的ShellItem,不存在则创建并添加到Shell根节点
  2. 添加子级ShellContent:将对应服务器的ShellContent添加到父级ShellItem下,仅设置server.ServerName作为子路由段

示例代码:

// 查找或创建对应SystemConnection的ShellItem(父级路由节点)
var systemShellItem = Shell.Current.Items
    .FirstOrDefault(item => item.Route == this.SystemConnection.Name) as ShellItem;

if (systemShellItem == null)
{
    systemShellItem = new ShellItem
    {
        Route = this.SystemConnection.Name,
        Title = this.SystemConnection.Name
    };
    Shell.Current.Items.Add(systemShellItem);
}

// 创建服务器对应的ShellContent(子级路由节点)
var serverContent = new ShellContent
{
    Title = server.ServerName,
    Route = server.ServerName,
    ContentTemplate = new DataTemplate(() => new ServerHomePage(new ServerViewModel(this.client, server)))
};

// 将子节点添加到父级ShellItem中
systemShellItem.Items.Add(serverContent);

对应导航代码

此时使用层级路由即可正常导航:

await Shell.Current.GoToAsync($"///{this.SystemConnection.Name}/{server.ServerName}");

额外注意事项

  • 确保每个层级节点(ShellItem、ShellContent)的Route唯一,避免路由冲突
  • 如果需要更复杂的层级(如三级路由),可以在ShellItem下添加ShellSection,再在ShellSection下添加ShellContent,每个层级对应一个路由段
  • 导航时使用///表示绝对路由,确保从Shell根节点开始匹配,避免相对路由的歧义

内容的提问来源于stack exchange,提问作者Saurbaum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 06:41:09