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

WPF RichTextBox:如何为聊天消息中冒号前后文本设置不同颜色

搞定不同颜色的聊天消息显示

你只需要把收到的文本拆分成名称段和内容段,分别创建两个Run控件设置不同样式,再放到同一个段落里就可以了。我帮你修改了WriteLine方法,直接用就行:

public void WriteLine(string text)
{
    Paragraph para = new Paragraph();

    // 找到第一个冒号的位置,这是我们的分割点
    int firstColonPos = text.IndexOf(':');
    if (firstColonPos != -1)
    {
        // 拆分出冒号前的名称部分
        string userName = text.Substring(0, firstColonPos);
        // 剩下的包括冒号在内的内容部分
        string messageContent = text.Substring(firstColonPos);

        // 名称设置绿色加粗
        var nameRun = new Run(userName)
        {
            Foreground = Brushes.Green,
            FontWeight = FontWeights.Bold
        };
        para.Inlines.Add(nameRun);

        // 内容保持白色
        var contentRun = new Run(messageContent)
        {
            Foreground = Brushes.White
        };
        para.Inlines.Add(contentRun);
    }
    else
    {
        // 万一收到没有冒号的消息,整行用白色显示(可以根据需求调整)
        para.Inlines.Add(new Run(text) { Foreground = Brushes.White });
    }

    txtOutput.Document.Blocks.Add(para);
    txtOutput.ScrollToEnd();
    txtInput.Clear();
    txtInput.Focus();
}

为啥这么改?

  • 用IndexOf(':')精准定位第一个冒号,保证只拆分一次,完全符合你“首次出现冒号前的文本变绿色”的要求。
  • 把名称和内容分开设置样式,既实现了绿色名称的效果,又不会影响后面的消息内容。
  • 加了无冒号的处理逻辑,避免遇到格式奇怪的消息时显示出错。

这样测试的话,当服务器返回"Bob: Is anyone here?",Bob会变成绿色加粗,后面的: Is anyone here?保持白色,完全是你想要的效果~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:30:39