WPF RichTextBox appending coloured text

前端 未结 4 1811
谎友^
谎友^ 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: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!

提交回复
热议问题