WPF RichTextBox附加彩色文本

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

试试这个:

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

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

 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) { } } 

这样就可以做到这一点

 myRichTextBox.AppendText("My text", "CornflowerBlue"); 

或者以hex表示

 myRichTextBox.AppendText("My text", "0xffffff"); 

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

以上单行回答: –

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

应该写的正确的方法是(我使用VS 2017): –

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