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

WPF ListBoxItem通过Style重写SystemColors无效果如何解决

代码无效原因

  • 你将SystemColors重写资源定义在了ListBoxItem的Style.Resources层级,WPF默认ListBoxItem控件模板对系统颜色的查找不会遍历到该层级,因此你定义的所有画刷都不会被识别。
  • 不需要重写大量无关的SystemColors键,修改失焦选中背景仅需要用到SystemColors.InactiveSelectionHighlightBrushKey这一个键即可,其余代码均为冗余。

效果示意图

最简单的实现方案

直接将需要重写的系统画刷放到ListBox.Resources层级即可,不需要嵌套在ListBoxItem的样式内部:

<Window x:Class="WpfAppListBoxItemBrushes.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d"
        Title="MainWindow" Height="200" Width="400">
    <ListBox>
        <ListBox.ItemsSource>
            <x:Array Type="sys:String">
                <sys:String>1st item</sys:String>
                <sys:String>2nd item</sys:String>
            </x:Array>
        </ListBox.ItemsSource>

        <ListBox.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Test"/>
            </ContextMenu>
        </ListBox.ContextMenu>

        <ListBox.Resources>
            <!-- 失焦选中背景色 -->
            <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Red" />
            <!-- 可选:修改失焦选中时的文字颜色 -->
            <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}" Color="White" />
        </ListBox.Resources>
    </ListBox>
</Window>

备选兼容方案

如果上述方案在你的目标系统主题下不生效,可以用更稳妥的样式触发器实现,代码同样简洁,不需要修改控件模板:

<ListBox.Resources>
    <Style TargetType="ListBoxItem">
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Background" Value="Red"/>
                <Setter Property="Foreground" Value="White"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</ListBox.Resources>

这个方案的优先级高于系统默认的失焦样式,无论ListBox是否获得焦点,选中项都会使用你设置的背景和文字颜色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 18:24:04