4
我正在處理根據正則表達式模式在RichTextBox中突出顯示文本的應用程序。 它工作正常,除了性能,即使對於小文本(約500個字符)它掛起一段時間,這是用戶可見。RichTextBox突出顯示性能
我在做錯誤的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;
}
}
稱呼它,我第一次在初始化方法
frm = new RichTextBoxManager(richTextBox1.Document);
和textchange事件文本框(這裏我把正則表達式),我稱之爲亮點方法
frm.Highlight(textBox1.Text);