如何修改WPF窗口标题栏背景 自定义样式后关闭按钮不显示
WPF修改窗口标题栏背景色后关闭按钮不显示问题修复
问题原因
使用WindowChrome自定义窗口模板时,自定义的根Grid会覆盖在系统原生标题栏绘制层之上:
- 未显式配置
WindowChrome参数时,系统无法识别标题栏区域,原生标题栏按钮不会正常渲染 - 自定义Grid默认全区域接收命中测试,会拦截右上角按钮区域的鼠标事件,导致按钮无法点击、显示异常
- 原代码存在属性值引号未闭合、客户区边距设置错误的语法问题
效果对比
当前异常效果

预期实现效果

修复步骤
- 配置
WindowChrome参数:开启UseAeroCaptionButtons保留系统原生标题栏按钮,设置CaptionHeight匹配标题栏高度,指定调整窗口大小的边框厚度 - 调整内容区域边距:预留顶部标题栏高度,避免客户区内容覆盖标题栏
- 给标题栏内需要交互的自定义元素(图标、标题文字、自定义按钮)添加
WindowChrome.IsHitTestVisibleInChrome="True"属性,保证元素可响应鼠标事件,同时不阻挡标题栏的拖动、双击等原生交互 - 修正原XAML中属性值未闭合的语法错误
修正后完整代码
<Style x:Key="StandardStyle" TargetType="{x:Type Window}"> <Setter Property="WindowChrome.WindowChrome"> <Setter.Value> <WindowChrome UseAeroCaptionButtons="True" CaptionHeight="32" ResizeBorderThickness="6"/> </Setter.Value> </Setter> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Window}"> <Grid Background="Yellow"> <!-- 窗口客户区内容,顶部预留32像素标题栏空间 --> <Border Margin="0,32,0,0"> <ContentPresenter Content="{TemplateBinding Content}"/> </Border> <!-- 窗口标题文字 --> <TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Title}" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="36,8,0,0" Foreground="Red" WindowChrome.IsHitTestVisibleInChrome="True"/> <!-- 窗口图标 --> <Image Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Icon}" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="8,6,0,0" Width="20" Height="20" WindowChrome.IsHitTestVisibleInChrome="True"/> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>
如果需要完全自定义标题栏按钮样式,可将
UseAeroCaptionButtons设为False,自行实现最小化、最大化、关闭按钮的点击逻辑,同样需要给自定义按钮添加WindowChrome.IsHitTestVisibleInChrome="True"保证点击事件正常触发。注意不要在右上角系统按钮预留区域放置拦截命中测试的不透明元素,避免遮挡按钮。
内容的提问来源于stack exchange,提问作者nihasmata
相关产品推荐
相关产品推荐

