在.NET MAUI中,如何让非Shell导航的新窗口页面渲染MenuBarItems?
可以在通过new Window()创建的页面中使用ContentPage.MenuBarItems,问题出在窗口的内容结构上——直接将ContentPage设为Window的Content时,缺少能渲染菜单栏的导航上下文,而Shell导航的页面因为内置了导航容器,所以能正常显示。
解决方法是将你的ContentPage包装到NavigationPage中,再把NavigationPage设置为Window的Content,具体步骤如下:
- 保留你现有包含
MenuBarItems的ContentPage代码不变 - 实例化
NavigationPage并传入你的ContentPage作为根页面 - 将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
相关产品推荐
相关产品推荐

