WPF修改ListView选中颜色并去除白色光泽效果求助
问题:移除WPF ListView选中项的白色光泽效果
我多次尝试移除WPF中ListView的白色光泽效果,但即使将所有相关属性设置为#1F419A,选中项顶部仍存在白色区域。
尝试的代码如下:
<ListView.Resources> <Style TargetType="{x:Type ListViewItem}"> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="#1F419A"/> <Setter Property="BorderBrush" Value="#1F419A"/> </Trigger> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" Value="#1F419A"/> <Setter Property="BorderBrush" Value="#1F419A"/> </Trigger> </Style.Triggers> </Style> </ListView.Resources>
期望选中项完全呈现#1F419A颜色,求解决方法。
解决方法
问题根源是WPF默认的ListViewItem控件模板内置了选中状态的高光光泽效果,仅设置Background和BorderBrush无法覆盖这部分视觉元素。最彻底的解决方式是重写ListViewItem的控件模板:
完整重写Style代码
<ListView.Resources> <Style TargetType="{x:Type ListViewItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListViewItem}"> <Border x:Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True"> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> </Border> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter TargetName="Bd" Property="Background" Value="#1F419A"/> <Setter TargetName="Bd" Property="BorderBrush" Value="#1F419A"/> </Trigger> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="Bd" Property="Background" Value="#1F419A"/> <Setter TargetName="Bd" Property="BorderBrush" Value="#1F419A"/> </Trigger> <Trigger Property="IsEnabled" Value="False"> <Setter TargetName="Bd" Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </ListView.Resources>
关键说明
- 新模板移除了默认绘制光泽的
Grid、Rectangle等元素,仅保留基础的Border和内容展示控件,彻底消除白色光泽 - 状态触发器直接作用于
Border的背景和边框属性,确保选中、鼠标悬停时完全显示目标颜色#1F419A - 如需保留焦点提示等其他默认行为,可以在模板内添加对应的
FocusVisualStyle或控件元素
若仅需快速屏蔽焦点带来的额外视觉,也可直接添加<Setter Property="FocusVisualStyle" Value="{x:Null}"/>到ListViewItem的Style中,但重写模板的方式覆盖更全面。
内容的提问来源于stack exchange,提问作者Lucas Dewil
相关产品推荐
相关产品推荐

