我正在开发根据正则表达式模式突出显示 RichTextBox 中的文本的应用程序。它工作正常,除了性能,即使是小文本(大约 500 个字符),它也会挂起一段时间,用户可以看到。
我对 FlowDocument 做错了吗?有人可以指出性能问题的根源吗?
public class RichTextBoxManager
{
private readonly FlowDocument inputDocument;
private TextPointer currentPosition;
public RichTextBoxManager(FlowDocument inputDocument)
{
if (inputDocument == null)
{
throw new ArgumentNullException("inputDocument");
}
this.inputDocument = inputDocument;
this.currentPosition = inputDocument.ContentStart;
}
public TextPointer CurrentPosition
{
get { return currentPosition; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (value.CompareTo(inputDocument.ContentStart) < 0 ||
value.CompareTo(inputDocument.ContentEnd) > 0)
{
throw new ArgumentOutOfRangeException("value");
}
currentPosition = value;
}
}
public TextRange Highlight(string regex)
{
TextRange allDoc = new TextRange(inputDocument.ContentStart, inputDocument.ContentEnd);
allDoc.ClearAllProperties();
currentPosition = inputDocument.ContentStart;
TextRange textRange = GetTextRangeFromPosition(ref currentPosition, regex);
return textRange;
}
public TextRange GetTextRangeFromPosition(ref TextPointer position,
string regex)
{
TextRange textRange = null;
while (position != null)
{
if (position.CompareTo(inputDocument.ContentEnd) == 0)
{
break;
}
if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
{
String textRun = position.GetTextInRun(LogicalDirection.Forward);
var match = Regex.Match(textRun, regex);
if (match.Success)
{
position = position.GetPositionAtOffset(match.Index);
TextPointer nextPointer = position.GetPositionAtOffset(regex.Length);
textRange = new TextRange(position, nextPointer);
textRange.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Yellow);
position = nextPointer;
}
else
{
position = position.GetPositionAtOffset(textRun.Length);
}
}
else
{
position = position.GetNextContextPosition(LogicalDirection.Forward);
}
}
return textRange;
}
}
要调用它,我首先在 Initialize 方法中创建一个实例
frm = new RichTextBoxManager(richTextBox1.Document);
在文本框的文本更改事件(我放正则表达式的地方)我调用 Highlight 方法
frm.Highlight(textBox1.Text);