2

I want to change the foreground color of a TextBox in WPF. Here is the code:

foreach (Match m in RedWord)
{
    TextBox1.SelectionStart = m.Index;
    TextBox1.SelectionLength = m.Length;
    TextBox1.Select(m.Index, m.Length);
    TextBox1.SelectionBrush = Brushes.Red;
    //EditorTextBox.Foreground = Brushes.Red;
}

The .SelectionBrush does not appear to apply the foreground text color as I need it. How can I change my text foreground color on selection?

Alex Tartan
  • 6,736
  • 10
  • 34
  • 45
user3263967
  • 25
  • 1
  • 6
  • Do you mean you want the **text** to be set to red, and the selection box thing to remain the same colour? Or, transparent? What I mean is that you want to apply the foreground only to text that has been selected? – Mike Eason Jun 09 '15 at 13:32
  • Unfortunately, [you can't](http://stackoverflow.com/questions/10850629/how-to-change-the-highlighted-texts-foreground-color-for-a-wpf-textbox/10850718#10850718). – Mike Eason Jun 09 '15 at 13:38

1 Answers1

0

For the highlight colour - you should do this in XAML.

<TextBox Text="hehehehehehehe adfasdfasdfds" SelectionBrush="Aquamarine" />

It works fine:

enter image description here

You cannot set the text colour (foreground) of selected text independently of unselected text. The text colour is effectively coming from the system brush key (ControlTextBrushKey, I think) - and it cannot be set separately.

James Harcourt
  • 6,017
  • 4
  • 22
  • 42