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

Maui 9中替代设置MainPage的实现方法咨询(排除重写CreateWindow)

在MAUI 9中替代设置MainPage的几种方法
  • 直接修改当前窗口的Page属性
    这是最接近原Xamarin Forms中设置MainPage的操作,MAUI里窗口的Page属性就是对应顶级页面。代码示例:

    // 获取主窗口(优先取活跃窗口,单窗口场景用Windows[0]即可)
    var mainWindow = Application.Current.Windows.FirstOrDefault(w => w.IsActive) ?? Application.Current.Windows[0];
    // 替换为新的顶级页面
    mainWindow.Page = new YourTargetPage();
    

    如果操作不在UI线程,记得用主线程包裹:

    await MainThread.InvokeOnMainThreadAsync(() =>
    {
        var mainWindow = Application.Current.Windows[0];
        mainWindow.Page = new YourTargetPage();
    });
    
  • 基于Shell框架的场景处理
    如果你的MAUI应用使用了Shell作为根结构,建议用Shell自身的机制切换顶级页面,更贴合框架生命周期:

    1. 通过设置CurrentItem切换根标签/路由:
      var shell = Application.Current.MainPage as Shell;
      // 替换为目标路由对应的ShellItem
      shell.CurrentItem = shell.Items.First(item => item.Route == "your-root-route");
      
    2. 通过导航到根路由:
      var shell = Application.Current.MainPage as Shell;
      await shell.GoToAsync("//your-root-route");
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 16:19:59