Color different parts of a RichTextBox string

前端 未结 9 664
暖寄归人
暖寄归人 2020-11-22 08:10

I\'m trying to color parts of a string to be appended to a RichTextBox. I have a string built from different strings.

string temp = \"[\" + DateTime.Now.ToSh         


        
9条回答
  •  花落未央
    2020-11-22 08:50

    Using Selection in WPF, aggregating from several other answers, no other code is required (except Severity enum and GetSeverityColor function)

     public void Log(string msg, Severity severity = Severity.Info)
        {
            string ts = "[" + DateTime.Now.ToString("HH:mm:ss") + "] ";
            string msg2 = ts + msg + "\n";
            richTextBox.AppendText(msg2);
    
            if (severity > Severity.Info)
            {
                int nlcount = msg2.ToCharArray().Count(a => a == '\n');
                int len = msg2.Length + 3 * (nlcount)+2; //newlines are longer, this formula works fine
                TextPointer myTextPointer1 = richTextBox.Document.ContentEnd.GetPositionAtOffset(-len);
                TextPointer myTextPointer2 = richTextBox.Document.ContentEnd.GetPositionAtOffset(-1);
    
                richTextBox.Selection.Select(myTextPointer1,myTextPointer2);
                SolidColorBrush scb = new SolidColorBrush(GetSeverityColor(severity));
                richTextBox.Selection.ApplyPropertyValue(TextElement.BackgroundProperty, scb);
    
            }
    
            richTextBox.ScrollToEnd();
        }
    

提交回复
热议问题