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

在.NET MAUI中,如何让非Shell导航的新窗口页面渲染MenuBarItems?

在.NET MAUI非Shell导航窗口中启用MenuBarItems

可以在通过new Window()创建的页面中使用ContentPage.MenuBarItems,问题出在窗口的内容结构上——直接将ContentPage设为Window的Content时,缺少能渲染菜单栏的导航上下文,而Shell导航的页面因为内置了导航容器,所以能正常显示。

解决方法是将你的ContentPage包装到NavigationPage中,再把NavigationPage设置为Window的Content,具体步骤如下:

  1. 保留你现有包含MenuBarItems的ContentPage代码不变
  2. 实例化NavigationPage并传入你的ContentPage作为根页面
  3. 将NavigationPage赋值给Window的Content属性,再打开窗口

示例C#代码

// 实例化你的自定义ContentPage
var customPage = new YourContentPage();
// 用NavigationPage包装页面,提供导航上下文
var navigationPage = new NavigationPage(customPage);
// 创建窗口并设置内容
var newWindow = new Window(navigationPage);
// 打开窗口
Application.Current.OpenWindow(newWindow);

示例XAML窗口定义

如果用XAML编写窗口,可直接在Window的Content中声明NavigationPage:

<Window xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        xmlns:local="clr-namespace:YourAppNamespace"
        x:Class="YourAppNamespace.YourWindow">
    <NavigationPage>
        <x:Arguments>
            <local:YourContentPage />
        </x:Arguments>
    </NavigationPage>
</Window>

这样处理后,自定义页面的MenuBarItems就能在新窗口中正常渲染了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 18:12:18