Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you change the highlighted text color for a WPF TextBox?

The WPF TextBox natively makes use of the System Highlight color for painting the background of selected text. I would like to override this and make it consistent since it varies by OS/user theme.

For ListBoxItems, there is a neat trick (see below) where you can override the resource key for the HighlightBrushKey to customize the System Highlight color in a focused setting:

<Style TargetType="ListBoxItem">
    <Style.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                         Color="LightGreen"/>
    </Style.Resources>
</Style>

The same trick does not work for the TextBox unfortunately. Does anyone have any other ideas, besides "override the ControlTemplate"?

NOTE: This behavior appears to be added to WPF 4.

like image 781
Steve Cadwallader Avatar asked Jan 02 '09 03:01

Steve Cadwallader


People also ask

How do I change the color of my highlighted text?

Highlight selected text Select the text that you want to highlight. Go to Home and select the arrow next to Text Highlight Color. Select the color that you want. Note: Use a light highlight color if you plan to print the document by using a monochrome palette or printer.

How do I change the color of text in WPF?

<Grid> <TextBlock x:Name="tbname" HorizontalAlignment="Left" Height="22" Margin="175,25,0,0" TextWrapping="Wrap" Text="Coloured Label Text" VerticalAlignment="Top" Width="157" FontSize="14" />

How do I highlight a textbox in WPF?

You can use the following code to achieve your purpose: textBoxToHighlight. Focus(); textBoxToHighlight. Select(0, textBoxToHighlight.

How do I change the background color in WPF?

Navigate to the Properties window, and click the Background drop-down arrow, and choose Red or another color in the color picker.


1 Answers

Since .NET 4, TextBoxBase.SelectionBrush

You can specify the brush that highlights selected text by setting the SelectionBrush and SelectionOpacity properties. The SelectionOpacity property specifies the opacity of the SelectionBrush.

eg.

<TextBox SelectionBrush="Red" SelectionOpacity="0.5"
         Foreground="Blue" CaretBrush="Blue">  
like image 56
Colonel Panic Avatar answered Sep 17 '22 16:09

Colonel Panic