WPF ComboBoxItem鼠标悬停背景修改无效,如何移除默认高亮效果
问题原因
- 你当前代码设置了
OverridesDefaultStyle="True"但没有为ComboBoxItem定义完整的控件模板,导致控件基础渲染逻辑缺失,Style里的触发器无法正常生效 - .NET Core 3.0及以上版本的WPF中,覆盖
SystemColors.HighlightBrushKey的方案已经失效,WPF不再调用该系统资源渲染下拉选项的高亮背景
可行解决方案
直接替换你的ComboBox代码即可,以下示例实现了鼠标悬停时背景为红色、聚焦时背景为浅灰色的效果,完全移除默认橙色高亮:
<ComboBox HorizontalAlignment="Left" Margin="95,44,0,0" VerticalAlignment="Top" Width="208"> <ComboBox.Resources> <Style TargetType="{x:Type ComboBoxItem}"> <Setter Property="Foreground" Value="Gray" /> <Setter Property="FocusVisualStyle" Value="{x:Null}"/> <Setter Property="BorderThickness" Value="0"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ComboBoxItem}"> <Border x:Name="ItemBorder" Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" Padding="4,2"> <ContentPresenter HorizontalAlignment="Left" VerticalAlignment="Center"/> </Border> <ControlTemplate.Triggers> <Trigger Property="IsFocused" Value="True"> <Setter TargetName="ItemBorder" Property="Background" Value="#FFCDCDCD"/> </Trigger> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="ItemBorder" Property="Background" Value="Red"/> </Trigger> <Trigger Property="IsSelected" Value="True"> <Setter TargetName="ItemBorder" Property="Background" Value="#FFCDCDCD"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </ComboBox.Resources> <!-- 这里放你的ComboBox选项 --> <ComboBoxItem Content="选项1"/> <ComboBoxItem Content="选项2"/> <ComboBoxItem Content="选项3"/> </ComboBox>
补充说明
- 若需要全局生效,可将上述
ComboBoxItem的Style迁移到App.xaml的ResourceDictionary中,项目内所有ComboBox都会复用该样式 - 可根据需求自行修改各Trigger中Background的颜色值,如需完全移除高亮效果可设置为
Transparent
内容的提问来源于stack exchange,提问作者Su Si
相关产品推荐
相关产品推荐

