WPF RichTextBox 文本超过限定行数移除旧数据
在使用serilog.sinks.richtextbox 显示日志时,会需要移除旧的日志信息的需求,实现打码如下;
根据换行符“\n” 进行判断;
private void CheckAndRemoveText() { int newLineCount = 0; bool removeText = false; foreach (Paragraph paragraph in _richTextBox.Document.Blocks) { foreach (Run run in paragraph.Inlines) { newLineCount += CountOccurrences(run.Text, "\n"); if (newLineCount >= 3) { removeText = true; break; } } if (removeText) { RemoveTextBeforeFirstNewLine(paragraph); break; } } } private int CountOccurrences(string text, string pattern) { return text.Split(new string[] { pattern }, System.StringSplitOptions.None).Length - 1; } private void RemoveTextBeforeFirstNewLine(Paragraph paragraph) { string text = new TextRange(paragraph.ContentStart, paragraph.ContentEnd).Text; int index = text.IndexOf("\n"); if (index != -1) { paragraph.Inlines.Clear(); paragraph.Inlines.Add(new Run(text.Substring(index + 1))); } }