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

.NET MAUI中Windows标题栏透明化及标题控件颜色修改问题

.NET MAUI Windows标题栏自定义实现方案

针对标题栏背景色无法修改、透明与自定义样式冲突的问题,可通过以下步骤实现预期效果:

核心修改思路

  • 保留ExtendsContentIntoTitleBar = true让内容延伸至标题栏区域
  • 通过AppWindow.TitleBar配置系统标题栏透明,让自定义标题栏的背景色生效
  • 创建带背景色的自定义标题栏容器,替代空白Grid,同时保留窗口操作按钮的可用性

修改后的代码

builder.ConfigureLifecycleEvents(events =>
{
    events.AddWindows(wndLifeCycleBuilder =>
    {
        wndLifeCycleBuilder.OnWindowCreated(window =>
        {
            // 允许内容延伸至标题栏区域
            window.ExtendsContentIntoTitleBar = true;

            IntPtr nativeWindowHandle = WinRT.Interop.WindowNative.GetWindowHandle(window);
            WindowId win32WindowsId = Win32Interop.GetWindowIdFromWindow(nativeWindowHandle);
            AppWindow winuiAppWindow = AppWindow.GetFromWindowId(win32WindowsId);

            var titleBar = winuiAppWindow.TitleBar;
            // 设置系统标题栏透明,让自定义标题栏背景显示
            titleBar.BackgroundColor = Colors.Transparent;
            titleBar.InactiveBackgroundColor = Colors.Transparent;
            // 根据自定义背景色调整标题栏按钮颜色,确保可见性
            titleBar.ButtonForegroundColor = Colors.White;
            titleBar.ButtonInactiveForegroundColor = Colors.Gray;

            // 创建自定义标题栏Grid,设置背景色(替换为你需要的颜色)
            var customTitleBar = new Microsoft.UI.Xaml.Controls.Grid();
            customTitleBar.Background = new SolidColorBrush(Colors.DarkSlateBlue);

            // 可选:添加标题文本控件到自定义标题栏
            // var titleText = new TextBlock 
            // { 
            //     Text = "自定义标题", 
            //     Foreground = new SolidColorBrush(Colors.White), 
            //     VerticalAlignment = VerticalAlignment.Center,
            //     Margin = new Thickness(16, 0, 0, 0)
            // };
            // customTitleBar.Children.Add(titleText);

            // 设置自定义标题栏
            window.SetTitleBar(customTitleBar);
        });
    });
});

关键说明

  • 移除了p.SetBorderAndTitleBar(false, false),避免彻底隐藏系统标题栏框架导致的布局异常
  • 系统标题栏设为透明后,自定义Grid的背景色会直接覆盖标题栏区域,解决背景色无法修改的问题
  • 标题栏按钮颜色可根据你的自定义背景色调整,避免出现按钮不可见的情况
  • 若需要添加标题文本或其他UI元素,直接将控件加入自定义Grid即可

现有效果:
现有效果

预期效果:
预期效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 11:01:24