zoukankan      html  css  js  c++  java
  • WPF的RichTextBox中查找字符串位置

    已经琢磨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;
            }

  • 相关阅读:
    WCF Security系列(1)Security概述
    转:如何修复Team Foundation Server Workgroup Edition 不小心删除了所有Team Foundation Licensed Users组内用户问题
    转:最真实的2006年应届毕业生真实薪水
    如果为网站生成自签名SSL证书
    转 :TFS(Team Foundation Server)使用经验
    The sequence 2 序列2 攻略 (第4049关)
    力扣 223. 矩形面积
    The sequence 2 序列2 攻略 (第5059关)
    The sequence 2攻略 序列2攻略(第3039关)
    题解 P1147 【连续自然数和】
  • 原文地址:https://www.cnblogs.com/xiarifeixue/p/1905157.html
Copyright © 2011-2022 走看看