Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF RichTextBox appending coloured text

Tags:

I'm using the RichTextBox.AppendText function to add a string to my RichTextBox. I'd like to set this with a particular colour. How can I do this?

like image 473
Aks Avatar asked Apr 01 '11 11:04

Aks


2 Answers

Just try this:

TextRange tr = new TextRange(rtb.Document.ContentEnd,­ rtb.Document.ContentEnd); tr.Text = "textToColorize"; tr.ApplyPropertyValue(TextElement.­ForegroundProperty, Brushes.Red); 
like image 98
Kishore Kumar Avatar answered Sep 21 '22 16:09

Kishore Kumar


If you want, you can also make it an extension method.

public static void AppendText(this RichTextBox box, string text, string color) {     BrushConverter bc = new BrushConverter();     TextRange tr = new TextRange(box.Document.ContentEnd, box.Document.ContentEnd);     tr.Text = text;     try      {          tr.ApplyPropertyValue(TextElement.ForegroundProperty,              bc.ConvertFromString(color));      }     catch (FormatException) { } } 

This will make it so you can just do

myRichTextBox.AppendText("My text", "CornflowerBlue"); 

or in hex such as

myRichTextBox.AppendText("My text", "0xffffff"); 

If the color string you type is invalid, it simply types it in the default color (black). Hope this helps!

like image 45
omni Avatar answered Sep 21 '22 16:09

omni