我有一个功能,可以在Richtextbox中突出显示“关键字”,它在小文本上的效果很好,但是在大文本上的效果很慢。
是由哪几行引起的问题,我该如何改进以加快速度?
private void menu_EnableHighlighting_Click(对象发送者,RoutedEventArgs e) {
newRichBox.SelectAll();
TextPointer position = newRichBox.Document.ContentStart;
List<TextRange> ranges = new List<TextRange>();
while (position != null)
{
if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
{
string text = position.GetTextInRun(LogicalDirection.Forward);
var matchs = Regex.Matches(text, @"begin|try|except|end|case|uses|var|if|else|then");
foreach (Match match in matchs)
{
TextPointer start = position.GetPositionAtOffset(match.Index);
TextPointer end = start.GetPositionAtOffset(match.Length);
TextRange textrange = new TextRange(start, end);
ranges.Add(textrange);
}
}
position = position.GetNextContextPosition(LogicalDirection.Forward);
}
foreach (TextRange range in ranges)
{
range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.CadetBlue));
range.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
}
}