我有一个RichTextBox,我正在尝试查找并突出显示与用户提供的查询匹配的所有单词.我的代码有效,但是对于相当大的文档,它会挂起UI,因为所有内容都是在UI线程上完成的.
List<TextRange> getAllMatchingRanges(String query)
{
TextRange searchRange = new TextRange(ricthBox.Document.ContentStart, ricthBox.Document.ContentEnd);
int offset = 0, startIndex = 0;
List<TextRange> final = new List<TextRange>();
TextRange result = null;
while (startIndex <= searchRange.Text.LastIndexOf(query))
{
offset = searchRange.Text.IndexOf(query, startIndex);
if (offset < 0)
break;
}
for (TextPointer start = searchRange.Start.GetPositionAtOffset(offset); start != searchRange.End; start = start.GetPositionAtOffset(1))
{
if (start.GetPositionAtOffset(query.Length) == null)
break;
result = new TextRange(start, start.GetPositionAtOffset(query.Length));
if (result.Text == query)
{
break;
}
}
if (result == null)
{
break;
}
final.Add(result); …Run Code Online (Sandbox Code Playgroud)