Wpf RichTextBox突出显示性能
我正在开发一个应用程序,它根据正则表达式模式突出显示RichTextBox中的文本。 除了性能外,它工作良好,即使对于小文本(约500个字符),它也会挂起一段时间,用户可以看到 我对FlowDocument做了什么错误吗?有人能告诉我性能问题的根源吗Wpf RichTextBox突出显示性能,wpf,performance,wpf-controls,Wpf,Performance,Wpf Controls,我正在开发一个应用程序,它根据正则表达式模式突出显示RichTextBox中的文本。 除了性能外,它工作良好,即使对于小文本(约500个字符),它也会挂起一段时间,用户可以看到 我对FlowDocument做了什么错误吗?有人能告诉我性能问题的根源吗 public class RichTextBoxManager { private readonly FlowDocument inputDocument; private TextPointer currentPositi
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;
}
}
在textbox的textchange事件中(我把regex放在这里),我调用Highlight方法
frm.Highlight(textBox1.Text);
这是一种不同的方法,但我使用它对200000个字符的文件进行亚秒响应 因为我从文本开始,这可能不是你的选择 我为文本文件编制了单词位置索引,用户可以搜索单词。我突出显示他们搜索的单词 但是我在文本中循环创建FlowDoc,并在构建FlowDoc时突出显示。此FlowDoc没有格式(突出显示除外)。因此,如果您需要保留格式,这将不起作用 所以我猜文本指针的开销很大 但我从你的代码中学到了很多,因为这就是我试图突出显示工作的方式,但我根本无法让TextPointer工作 也许可以考虑在textRun中处理所有匹配项,而不是只处理第一个匹配项并增加位置
frm.Highlight(textBox1.Text);