How can I change the colour of selected text in a WPF ComboBox?
In my application, I have defined the following style for TextBlocks.
<Style TargetType="{x:Type TextBlock}">
<Setter Property="FontFamily" Value="Arial"/>
<Setter Property="FontSize" Value="11"/>
<Setter Property="Foreground" Value="{StaticResource TextBrush}"/>
<Setter Property="Opacity" Value="1.0"/>
<Style.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Opacity" Value="0.40"/>
</Trigger>
</Style.Triggers>
</Style>
The style is intentionally defined at the highest level of my application so that it applies 开发者_开发知识库to all TextBlocks by default.
The problem is that this style breaks the behaviour of TextBlocks in ComboBoxes. Normally, the selected item in a ComboBox has its Foreground colour change to white. With this style applied however, the foreground colour of the text does not change.
How can I trigger the text to change colour when the TextBlock in a ComboBox is highlighted?
If you just want to change the texblock foreground for selected item(say Red), just add this to your style resources:
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Red"/>
</Style.Resources>
I resolved this issue by moving the styles out of app.xaml
and into a separate resource dictionary that I include as needed in my application Window & Pages.
This stops the TextBlock
style from affecting the colour of the text in the ComboBox
. Finally, to achieve the text colour I wanted on all items I overrode the following default system colours with my own.
<SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}"
Color="{StaticResource TextColor}"/>
<SolidColorBrush x:Key="{x:Static SystemColors.WindowTextBrushKey}"
Color="{StaticResource TextColor}"/>
You can add second style based on your first and reset background property.
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="{StaticResource TextBrush}"/>
</Style>
<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource {x:Type TextBlock}}" x:Key="ResetBG">
<Setter Property="Foreground" Value="{Binding Control.Background}"/>
</Style>
<TextBlock Text="Red"/>
<TextBlock Text="Default" Style="{StaticResource ResourceKey=ResetBG}"/>
精彩评论