Aks
Aks

Reputation: 5236

WPF RichTextBox appending coloured text

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?

Upvotes: 27

Views: 37319

Answers (7)

PolarBear
PolarBear

Reputation: 1267

I have further improved @Jack's answer:

  • Allow a user to pass front and background text colors
  • Add a workaround to make the code work properly in case a message contains line break symbols.

Code

private void AppendText(RichTextBox textBox,
                        string message,
                        SolidColorBrush fontColor,
                        SolidColorBrush backgroundColor)
{
    // If a message contains line breaks, the code bellow will
    // add an empty blank line for every line break in the message.
    // To avoid that we have to replace all new lines in the mesage with '\r' symbol.
    message = Regex.Replace(message, @"(\r\n)|(\n\r)|(\n)", "\r");

    var textRange = new TextRange(textBox.Document.ContentEnd,
                                  textBox.Document.ContentEnd) { Text = message };
    textRange.ApplyPropertyValue(TextElement.ForegroundProperty, fontColor);
    textRange.ApplyPropertyValue(TextElement.BackgroundProperty, backgroundColor);
}

Demo

The following code will display the messages, taking into account new line symbols:

AppendText(_richTextBox, "First part of the line. ", Brushes.Green, Brushes.Yellow);
AppendText(_richTextBox, "Second part of the line. ", Brushes.Blue, Brushes.White);
AppendText(_richTextBox, "Third part that\ncontains new line in the middle\n", Brushes.LightPink, Brushes.Gray);
AppendText(_richTextBox, "New line\nNew line\nNew line", Brushes.Black, Brushes.White);

enter image description here

Upvotes: 0

Jack
Jack

Reputation: 951

I ended up synthesising Omni and Kishores' answers and creating an extension method as so:

public static void AppendText(this System.Windows.Controls.RichTextBox box, string text, SolidColorBrush brush)
{
    TextRange tr = new TextRange(box.Document.ContentEnd, box.Document.ContentEnd);
    tr.Text = text;
    tr.ApplyPropertyValue(TextElement.ForegroundProperty, brush);
}

Which can be called as so:

MyTextBox.AppendText("Some Text\n", Brushes.Green);

Upvotes: 0

Kino101
Kino101

Reputation: 994

Just a complete example which mixes original question with previous remark from Tony

var paragraph = new Paragraph();
var run = new Run(message)    
{
    Foreground = someBrush
};
paragraph.Inlines.Add(run);
myRichTextBox.Document.Blocks.Add(paragraph);

Now, it is fast and coloured :)

Note that (unlike the TextRange solution) this solution also solved me a line break issue occurring at the first line of the RichTextBox.

Upvotes: 4

Tony
Tony

Reputation: 240

Be Aware of TextRange's Overhead

I spent a lot of time tearing my hair out, because TextRange wasn't fast enough for my use-case. This method avoids the overhead. I ran some barebones tests, and its faster by a factor of ~10 (but don't take my word for it lol, run your own tests)

Paragraph paragraph = new Paragraph();
Run run = new Run("MyText");
paragraph.Inlines.Add(run);
myRichTextBox.Document.Blocks.Add(paragraph);

Credit

Note: I think most use cases should work fine with TextRange. My use-case involved hundreds of individual appends, and that overhead stacks up.

Upvotes: 7

user1744515
user1744515

Reputation: 1

the above single line answer:-

  myRichTextBox.AppendText("items", "CornflowerBlue")

is not working.The correct way it should be writen is (i am using VS 2017) :-

    Dim text1 As New TextRange(myRichTextBox.Document.ContentStart, myRichTextBox.Document.ContentEnd)
  myRichTextBox.AppendText("items")
  text1.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.CornflowerBlue) 

Upvotes: -2

omni
omni

Reputation: 588

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!

Upvotes: 22

Kishore Kumar
Kishore Kumar

Reputation: 21863

Just try this:

TextRange tr = new TextRange(rtb.Document.ContentEnd,­ rtb.Document.ContentEnd);
tr.Text = "textToColorize";
tr.ApplyPropertyValue(TextElement.­ForegroundProperty, Brushes.Red);

Upvotes: 41

Related Questions