You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何根据字符串内容为RichTextBox指定行设置文本颜色?

解决RichTextBox单行文本独立着色问题

直接修改代码,利用RichTextBox的FlowDocument结构,通过Run对象为每行文本单独设置颜色,避免全局修改控件的Foreground:

// 处理textScript的文本(若需着色可复用下方逻辑)
var scriptParagraph = new Paragraph(new Run(dispText[0] + Environment.NewLine))
{
    Foreground = Brushes.Black
};
textScript.Document.Blocks.Add(scriptParagraph);

// 处理textResults的文本,根据内容匹配颜色
Brush targetColor = Brushes.Black;
if (dispText[1].Contains("passed"))
    targetColor = Brushes.Green;
else if (dispText[1].Contains("failed"))
    targetColor = Brushes.Red;

var resultParagraph = new Paragraph(new Run(dispText[1] + Environment.NewLine))
{
    Foreground = targetColor
};
textResults.Document.Blocks.Add(resultParagraph);

关键说明

  • Run是WPF中承载带格式文本的基础单元,每个Run可独立设置颜色、字体等样式,不会影响其他文本。
  • Paragraph作为段落容器,保证每行文本独立显示,也可通过它设置缩进、行距等排版属性。
  • 使用Brushes类的预定义画笔(如Brushes.Green)比手动创建SolidColorBrush更简洁高效。

如果需要清空RichTextBox原有内容,可在添加新段落前调用:

textResults.Document.Blocks.Clear();

内容的提问来源于stack exchange,提问作者Edwin Thompson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 17:25:27