如何在UWP应用的标题栏(TitleBar)中放置菜单栏(MenuBar)?
要把MenuBar放到UWP应用的标题栏中,需要通过扩展标题栏区域、调整控件布局并处理标题栏交互这几个步骤实现,具体代码如下:
1. 调整XAML布局
首先修改MainPage.xaml,给MenuBar命名并调整页面内容的边距,避免被MenuBar遮挡:
<Page x:Class="YourAppName.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:muxc="using:Microsoft.UI.Xaml.Controls" mc:Ignorable="d"> <Grid> <!-- 命名MenuBar以便后续C#代码操作 --> <muxc:MenuBar x:Name="AppMenuBar"> <muxc:MenuBarItem Title="Item1"> <MenuFlyoutItem Text="Flyout Item1"/> </muxc:MenuBarItem> </muxc:MenuBar> <!-- 页面内容区域,设置上边距避免被MenuBar遮挡 --> <ScrollViewer Margin="0,48,0,0"> <!-- 此处添加你的页面内容 --> </ScrollViewer> </Grid> </Page>
2. C#代码处理标题栏逻辑
在MainPage.xaml.cs中添加标题栏扩展、布局调整和交互处理的代码:
using Windows.ApplicationModel.Core; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace YourAppName { public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); SetupTitleBar(); } private void SetupTitleBar() { // 让应用内容扩展到系统标题栏区域 CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true; // 获取应用标题栏实例 ApplicationViewTitleBar titleBar = ApplicationView.GetForCurrentView().TitleBar; // 设置标题栏按钮为透明,和MenuBar融合 titleBar.ButtonBackgroundColor = Windows.UI.Colors.Transparent; titleBar.ButtonHoverBackgroundColor = Windows.UI.Colors.LightGray; titleBar.ButtonPressedBackgroundColor = Windows.UI.Colors.DarkGray; // 调整MenuBar的上边距,使其对齐标题栏按钮 AppMenuBar.Margin = new Thickness(0, titleBar.Height, 0, 0); // 监听标题栏布局变化,窗口状态改变时自动调整MenuBar位置 CoreApplication.GetCurrentView().TitleBar.LayoutMetricsChanged += CoreTitleBar_LayoutMetricsChanged; } private void CoreTitleBar_LayoutMetricsChanged(CoreApplicationViewTitleBar sender, object args) { // 动态更新MenuBar的上边距 AppMenuBar.Margin = new Thickness(0, sender.Height, 0, 0); } } }
注意事项
- 确保项目已安装WinUI 2.x NuGet包(
Microsoft.UI.Xaml),否则muxc命名空间无法识别。 - 页面内容的上边距可根据MenuBar的实际高度调整,默认48像素适配大多数场景。
- 可根据应用主题自定义标题栏按钮的颜色,保证视觉协调。
内容的提问来源于stack exchange,提问作者MinecraftWolf
相关产品推荐
相关产品推荐

