.NET MAUI如何将MenuBarItem置于ContentPage标题下方?
问题
我希望将MenuBarItem放置在ContentPage标题的下方,请问是否可以实现?
参考说明
.NET Multi-platform App UI (.NET MAUI)菜单栏是一个容器,在Mac Catalyst和Windows平台上会以水平行形式显示在应用顶部。
当前页面代码
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MPC_MassPropertiesCalculator_MAUIapp.Views.MPCFileDemo" Title="MPC - File Demo"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="2*" /> <RowDefinition Height="*" /> <RowDefinition Height="100" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> </Grid> <ContentPage.MenuBarItems> <MenuBarItem Text="Open MPC File" Grid.Row="1"> </MenuBarItem> <MenuBarItem Text="Compare" Grid.Row="1"> </MenuBarItem> </ContentPage.MenuBarItems> </ContentPage>
当前Windows平台效果

解答
默认的ContentPage.MenuBarItems是与系统标题栏深度整合的组件,在Windows和Mac Catalyst平台上会固定显示在窗口顶部的标题栏区域,无法直接调整到ContentPage标题的下方。
如果需要实现“页面标题下方的菜单栏”效果,可通过自定义方式实现:
- 移除默认系统菜单栏:删除
ContentPage.MenuBarItems节点,关闭系统级菜单栏展示。 - 在页面内添加自定义菜单栏:在页面Grid中新增一行用于放置自定义菜单,使用
HorizontalStackLayout结合MenuButton或Button模拟菜单交互逻辑。
修改后的示例代码如下:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MPC_MassPropertiesCalculator_MAUIapp.Views.MPCFileDemo" Title="MPC - File Demo"> <Grid> <Grid.RowDefinitions> <!-- 自定义菜单栏行 --> <RowDefinition Height="Auto" /> <RowDefinition Height="2*" /> <RowDefinition Height="*" /> <RowDefinition Height="100" /> </Grid.RowDefinitions> <!-- 自定义菜单栏 --> <HorizontalStackLayout Grid.Row="0" Padding="10" Spacing="10" BackgroundColor="LightGray"> <MenuButton Text="Open MPC File"> <!-- 在此添加具体菜单项 --> </MenuButton> <MenuButton Text="Compare"> <!-- 在此添加具体菜单项 --> </MenuButton> </HorizontalStackLayout> <!-- 原页面内容区域 --> </Grid> </ContentPage>
这种方案能让菜单栏完全处于页面内容区域内,精准位于标题下方,同时保留菜单的下拉交互功能。
内容的提问来源于stack exchange,提问作者Jean-Marc Flamand
相关产品推荐
相关产品推荐

