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?
Just try this:
TextRange tr = new TextRange(rtb.Document.ContentEnd, rtb.Document.ContentEnd); tr.Text = "textToColorize"; tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With