在WPF C#中更改文本某些部分的颜色和字体
有没有一种方法可以更改要放在TextBox或RichTextBox上的文本的某些部分的颜色和字体。我正在使用C#WPF。
例如
 richTextBox.AppendText("Text1 " + word + " Text2 ");例如,可变单词可以是Text1和Text2中的其他颜色和字体。有可能并且如何做到这一点?
回答:
如果您只想进行快速着色,则将RTB内容的末尾作为范围并对其应用格式可能是最简单的解决方案,例如
  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的MSDN页面,因为这为您设置文本格式提供了极大的灵活性。
以上是 在WPF C#中更改文本某些部分的颜色和字体 的全部内容, 来源链接: utcz.com/qa/433276.html







