c# - 如何更改 RichTextBox 的部分文本颜色

标签 c# wpf colors textbox richtextbox

美好的一天!

我尝试将部分文本更改为红色。

所以,我尝试使用 TextBox,但它不起作用。 所以,我读到,RichTextBox 可以做到这一点:i use this question

但我不知道如何附加彩色文本?

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

好的,我得到了 TextRange,但是如何将其附加到 RichTextBox?

你能告诉我如何将文本的某些部分变成红色吗? 谢谢!

最佳答案

从你的例子开始:

TextRange rangeOfText2 = new TextRange(tbScriptCode.Document.ContentEnd,
    tbScriptCode.Document.ContentEnd);

rangeOfText2.Text = "RED !";

rangeOfText2.ApplyPropertyValue(TextElement.ForegroundProperty,Brushes.Red);
rangeOfText2.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);

对我有用。

Ok, i get TextRange, but how to append it to RichTextBox?

已经添加

new TextRange(tbScriptCode.Document.ContentEnd, tbScriptCode.Document.ContentEnd);

你还可以做什么(我最近自己用过这个):

var fd = new FlowDocument();

Paragraph paragraph = new Paragraph();

paragraph.Inlines.Add(new Run("normal text and this is in "));
paragraph.Inlines.Add(new Run("red") { Foreground = Brushes.Red });
paragraph.Inlines.Add(new Run(" and this is blue.") { Foreground = Brushes.Blue });

fd.Blocks.Add(paragraph);

tbScriptCode.Document = fd;

关于c# - 如何更改 RichTextBox 的部分文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28604252/

相关文章:

c# - 如何使用响应式扩展等待 IObservable<T> 完成而不阻塞 UI?

c# - 如何使用 Gmail API 检索我的 Gmail 邮件?

C# 从 Color 获取所有颜色

php - 彩色 var_dump() 和错误

delphi - Delphi中有色图控件吗?

C# 如何根据 propertygrid 中另一个属性的值公开一个属性?

c# - 如何使用 SAPI 进行语音转文本?

.net - ImageBrush 可以多线程工作吗?

WPF 3D 旋转球体 GUI

c# - WPF MVVM : Binding to property of object