WPF RichTextBox附加彩色文本

Aks*_*Aks 20 c# wpf colors richtextbox

我正在使用该RichTextBox.AppendText函数向我添加一个字符串RichTextBox.我想用特定的颜色设置它.我怎样才能做到这一点?

Kis*_*mar 37

试试这个:

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


omn*_*mni 14

如果需要,您也可以将其作为扩展方法.

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) { }
}
Run Code Online (Sandbox Code Playgroud)

这样就可以做到这一点

myRichTextBox.AppendText("My text", "CornflowerBlue");
Run Code Online (Sandbox Code Playgroud)

或者以十六进制表示

myRichTextBox.AppendText("My text", "0xffffff");
Run Code Online (Sandbox Code Playgroud)

如果您键入的颜色字符串无效,则只需将其键入默认颜色(黑色).希望这可以帮助!


Ton*_*ony 7

注意 TextRange 的开销

我花了很多时间,因为TextRange对于我的用例来说速度不够快。此方法避免了开销。我运行了一些准系统测试,速度快了约 10 倍(但不要相信我的话,哈哈,运行你自己的测试)

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

信用

注意: 我认为大多数用例都应该可以很好地使用TextRange. 我的用例涉及数百个单独的附加,并且开销会增加。

  • 有没有办法给跑步着色(正如问题所问)? (2认同)
  • `run.Background = Brushes.Green; run.Foreground = Brushes.Red;` (2认同)