WPF RichTextBox appending coloured text

前端 未结 4 1803
谎友^
谎友^ 2021-02-04 01:38

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?

相关标签:
4条回答
  • 2021-02-04 02:07

    Just try this:

    TextRange tr = new TextRange(rtb.Document.ContentEnd,­ rtb.Document.ContentEnd);
    tr.Text = "textToColorize";
    tr.ApplyPropertyValue(TextElement.­ForegroundProperty, Brushes.Red);
    
    0 讨论(0)
  • 2021-02-04 02:10

    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!

    0 讨论(0)
  • 2021-02-04 02:16

    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.

    0 讨论(0)
  • 2021-02-04 02:23

    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) 
    
    0 讨论(0)
提交回复
热议问题