Home > Back-end >  WPF TextBox change background color of text and not whole TextBox
WPF TextBox change background color of text and not whole TextBox

Time:05-18

I would like to know if there is a way to change the color of the background of the text inside a TextBox and not for the whole TextBox. Like when you highlight/select the text.

CodePudding user response:

TextBox doesn't support coloured text or rich text formatting in general. Depending on your scenario, you would have to go with a TextBlock or RichtextBox.

TextBlock

You can either handle the text elements directly:

<TextBlock>
  <Run Text="This is some" />
  <Run Text="red"
       Background="Red" />
  <Run Text="text." />
</TextBlock>

Or in case you need to find a particular text, handle the text pointers:

<TextBlock x:Name="ColouredTextBlock" />
private void onl oaded(object sender, EventArgs e)
{
  var text = "This is some red text.";
  var highlightText = "red";

  this.ColouredTextBlock.Text = text;

  int highlightTextIndex = this.ColouredTextbox.Text.IndexOf(highlightText);
  TextPointer textStartPointer = this.ColouredTextbox.ContentStart.DocumentStart.GetInsertionPosition(LogicalDirection.Forward);
  var highlightTextRange = new TextRange(textStartPointer.GetPositionAtOffset(highlightTextIndex), textStartPointer.GetPositionAtOffset(highlightTextIndex   highlightText.Length));
  highlightTextRange.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Red);
}

RichtextBox

In case you need to allow user input, you would have to use a RichTextBox:

<RichTextBlock x:Name="ColouredRichTextBox" />
private void onl oaded(object sender, EventArgs e)
{
  var text = "This is some red text.";
  var highlightText = "red";

  this.ColouredRichTextBox.Document = new FlowDocument(new Paragraph(new Run(text)));

  TextPointer textStartPointer = this.ColouredRichTextBox.Document.ContentStart.DocumentStart.GetInsertionPosition(LogicalDirection.Forward);
  var highlightTextRange = new TextRange(textStartPointer.GetPositionAtOffset(highlightTextIndex), textStartPointer.GetPositionAtOffset(highlightTextIndex   highlightText.Length));
  highlightTextRange .ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Red);
}
  • Related