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

MAUI返回页面报错:暂不支持Shell元素相对路由,如何解决?

问题

新建了一个MAUI应用,沿用之前另一款正常运行应用的导航逻辑。跳转至新页面时一切正常,但返回原页面时出现问题。相关代码如下:

public async Task NavigateAsync(NavigationPages page)
{
    try
    {
        await Shell.Current.GoToAsync(page.ToString(), true);
    }
    catch (Exception ex)
    {

    }
}

ViewModel.cs

public ICommand GoBacKCommand { get; }

public ParamViewModel(INavigationService navigationService)
{
    GoBacKCommand = new Command(GoBacKExecute);
    this.navigationService = navigationService;
}
private void GoBacKExecute()
{
    navigationService.NavigateAsync(BusinessModels.NavigationPages.MainPage);
}

MauiProgram.cs

Routing.RegisterRoute(nameof(MainPage), typeof(MainPage));
services.AddTransient<MainPage>();
services.AddTransient<MainViewModel>();

报错信息为:Relative routing to shell elements is currently not supported. Try prefixing your uri with ///: ///MainPage,但按照提示添加///前缀后,导航功能完全失效。

解决方案

针对这个Shell导航问题,按以下步骤调整:

  • 改用Shell内置返回逻辑
    返回上一页不需要重新导航到MainPage,直接调用Shell标准返回方法GoToAsync("..")即可,避免路由冲突。修改代码如下:
    在NavigationService中新增返回方法:

    public async Task GoBackAsync()
    {
        try
        {
            await Shell.Current.GoToAsync("..", true);
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"导航错误: {ex.Message}");
        }
    }
    

    然后在ViewModel的返回方法中调用:

    private void GoBacKExecute()
    {
        navigationService.GoBackAsync();
    }
    
  • 修正路由前缀使用
    如果必须通过路由名称跳转回MainPage,不要用///前缀,改用双斜杠//的绝对路由格式,确保路由注册与Shell页面结构匹配。比如:

    await Shell.Current.GoToAsync($"//{page.ToString()}", true);
    
  • 完善异常处理
    原代码捕获异常后无任何处理,会掩盖真实问题,建议添加日志输出,方便排查错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:33:25