愚见未来

人的思想时时刻刻都在进步,如果你早上起床,想起昨天所做的事情是那么幼稚和迂腐,那么恭喜你,你又变得成熟一点了!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

WPF的RichTextBox中查找字符串位置

Posted on 2010-12-14 00:36  愚见未来  阅读(2525)  评论(0编辑  收藏  举报

已经琢磨2天了,一直没明白如何在WPF的RichTextBox中查找一个字符串的位置,最后在google上找到了一个牛人的解决办法,收藏过来,留着备用。

 

private List<TextRange> FindAllMatchedTextRanges(RichTextBox richBox, string keyword)
        {
            List
<TextRange> trList = new List<TextRange>();
           
//设置文字指针为Document初始位置
            TextPointer position = richBox.Document.ContentStart;
           
while (position != null)
            {
               
//向前搜索,需要内容为Text
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                   
//拿出Run的Text
                    string text = position.GetTextInRun(LogicalDirection.Forward);
                   
//可能包含多个keyword,做遍历查找
                    int index = 0;
                   
while (index < text.Length)
                    {
                        index
= text.IndexOf(keyword, index);
                       
if (index == -1)
                        {
                           
break;
                        }
                       
else
                        {
                           
//添加为新的Range
                            TextPointer start = position.GetPositionAtOffset(index);
                            TextPointer end
= start.GetPositionAtOffset(keyword.Length);

          trList.Add(new TextRange(start, end));
                            index
+= keyword.Length;
                        }
                    }
                }
               
//文字指针向前偏移
                position = position.GetNextContextPosition(LogicalDirection.Forward);
            }
           
return trList;
        }