WinUI 3 无法正确设置标题栏背景色问题求助
WinUI标题栏与内容区域背景色不一致问题解决
问题描述
想要将WinUI应用的标题栏和内容区域背景色统一设置为#FF2B2B2B,但运行后内容区域颜色正确,标题栏颜色却偏浅。使用默认XAML颜色Black时也存在该问题,而使用Red则显示正常。
问题原因
当通过SetTitleBar方法自定义标题栏时,系统会对标题栏区域的背景自动应用透明度叠加效果(尤其是深色系颜色),导致自定义的背景色被冲淡,看起来偏浅。亮色系颜色受此影响不明显,所以Red能正常显示。
解决方案
通过设置窗口标题栏的系统属性,禁用其默认的背景色和叠加效果,让自定义标题栏的背景完全显示:
- 获取窗口的
AppWindow.TitleBar对象 - 将其背景色、非激活状态背景色、按钮背景色全部设为透明,消除系统默认的颜色叠加
修改后的代码
MainWindow.xaml.cs
using Microsoft.UI.Xaml; using Microsoft.UI; // 添加该命名空间以使用Colors类 namespace TItleBarBackground { public sealed partial class MainWindow : Window { public MainWindow() { this.InitializeComponent(); ExtendsContentIntoTitleBar = true; SetTitleBar(AppTitleBar); // 禁用系统标题栏默认背景,让自定义背景完全展示 var titleBar = AppWindow.TitleBar; titleBar.BackgroundColor = Colors.Transparent; titleBar.InactiveBackgroundColor = Colors.Transparent; titleBar.ButtonBackgroundColor = Colors.Transparent; titleBar.ButtonInactiveBackgroundColor = Colors.Transparent; } } }
MainWindow.xaml(保持原代码即可)
<Window x:Class="TItleBarBackground.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:TItleBarBackground" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid> <Grid.Resources> <SolidColorBrush x:Key="Colour" Color="#FF2B2B2B"/> </Grid.Resources> <Grid x:Name="AppTitleBar" Height="28" HorizontalAlignment="Stretch" VerticalAlignment="Top" Background="{StaticResource Colour}"> <TextBlock Text="Title"/> </Grid> <Rectangle Fill="{StaticResource Colour}" Margin="0,40,0,0" /> </Grid>
说明
修改后,系统不再对标题栏区域添加额外的颜色叠加,自定义的#FF2B2B2B背景色会完全显示,与内容区域的颜色保持一致。测试Black颜色时也会正常显示纯黑,不会出现偏浅的情况。
内容的提问来源于stack exchange,提问作者uhlw32n2
相关产品推荐
相关产品推荐

