改变颜色和字体在WPF C#文本的某些部分

问题描述:

有没有办法来改变颜色和字体文本的某些部分,我想要把文本框或RichTextBox的。我使用C#WPF。

Is there a way to change color and font for some part of text which I want to put on TextBox or RichTextBox. I am using C# WPF.

例如

 richTextBox.AppendText("Text1 " + word + " Text2 ");

例如可变字从文本1和文本等颜色和字体。是否可能,如何做到这一点?

Variable word for example to be other color and font from Text1 and Text2. Is it possible and how to do this?

如果你只想做一些快速着色,使用RTB内容为范围的结束和格式应用于它也许是最简单的解决方案,例如

If you just want to do some quick coloring , using the end of the RTB content as a Range and apply formatting to it is maybe the simplest solution, e.g.

  TextRange rangeOfText1 = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
  rangeOfText1.Text = "Text1 ";
  rangeOfText1.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
  rangeOfText1.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);

  TextRange rangeOfWord = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
  rangeOfWord.Text = "word ";
  rangeOfWord.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
  rangeOfWord.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Regular);

  TextRange rangeOfText2 = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
  rangeOfText2.Text = "Text2 ";
  rangeOfText2.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
  rangeOfText2.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);

如果你正在寻找一种更先进的解决方案,我建议您阅读有关的FlowDocument 一>,因为这让你在格式化文本极大的灵活性。

If you are looking for a more advanced solution, I suggest reading the MSDN page about the FlowDocument, as this gives you a great flexibility in formatting your text.