zoukankan      html  css  js  c++  java
  • [转]WPF控件 RichTextBox查找定位匹配字符

    private void Search_Click(object sender, RoutedEventArgs e)//查询定位文本
    {
        List<TextRange> textRanges = FindWordFromPosition(richTextBox1.Document.ContentStart, txtSearch.Text);
        foreach (var range in textRanges)
        {
            range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red));
            //range.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
            //range.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.PowderBlue));
        }
    }
    List<TextRange> FindWordFromPosition(TextPointer position, string word)
    {
        List<TextRange> matchingText = new List<TextRange>();
        while (position != null)
        {
            if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
            {
                //带有内容的文本
                string textRun = position.GetTextInRun(LogicalDirection.Forward);
    
                //查找关键字在这文本中的位置
                int indexInRun = textRun.IndexOf(word);
                int indexHistory = 0;
                while (indexInRun >= 0)
                {
                    TextPointer start = position.GetPositionAtOffset(indexInRun + indexHistory);
                    TextPointer end = start.GetPositionAtOffset(word.Length);
                    matchingText.Add(new TextRange(start, end));
    
                    indexHistory = indexHistory + indexInRun + word.Length;
                    textRun = textRun.Substring(indexInRun + word.Length);//去掉已经采集过的内容
                    indexInRun = textRun.IndexOf(word);//重新判断新的字符串是否还有关键字
                }
            }
    
            position = position.GetNextContextPosition(LogicalDirection.Forward);
        }
        return matchingText;
    }

              


    ---------------------
    作者:FreeSaber
    来源:CNBLOGS
    原文:https://www.cnblogs.com/zhongxinWang/p/5476893.html
    版权声明:本文为作者原创文章,转载请附上博文链接!
    内容解析By:CSDN,CNBLOG博客文章一键转载插件

  • 相关阅读:
    ue4同c#通信时的中文乱码问题
    ue4 fstring 和std::string互转
    LinqToExcel 简洁与优美开源库
    虚幻UE4的后处理特效介绍 http://www.52vr.com/thread-31215-1-1.html
    为什么你应该使用OpenGL而不是DirectX?
    会写代码是你创业路上的包袱
    (转载)怎样解决SQL Server内存不断增加问题
    UE4 Pak 相关知识总结
    淘宝运营实战操作大纲
    淘宝运营
  • 原文地址:https://www.cnblogs.com/admans/p/13072619.html
Copyright © 2011-2022 走看看