C# WPF 中的 TextRange 和 RichTextBox

2024-01-07

我一直在尝试编写一个程序来在 richTextBox 中搜索单词。我已经完成了大部分,但看起来我错过了一些东西。我想为找到的单词着色,所以我写了以下内容:

private void button1_Click(object sender, RoutedEventArgs e)
    {
        richTextBox1.SelectAll();
        string words = richTextBox1.Selection.Text; // to get the the whole text

        int length = words.Length;                  // length of text

        string search = textBox1.Text;              // the word being searched for
        int search_length = search.Length;


        int index =0;                               // to go through the text
        int endIndex = 0;                           // the end of the got word

         // pointer to the begining and the ending of the word which will be colored.
        TextPointer start_pointer, end_pointer;   

        if(length>0 &&search_length>0)              // text exists
        while(index<length-search_length)  
        {
            index = words.IndexOf(search, index);
            if (index < 0) // not found
                break;
             endIndex = index+search.Length-1;       // last char in the word
             start_pointer = richTextBox1.Document.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward).GetPositionAtOffset(index, LogicalDirection.Forward);
             end_pointer = richTextBox1.Document.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward).GetPositionAtOffset(endIndex + 1, LogicalDirection.Forward);

            TextRange got = new TextRange(start_pointer, end_pointer);

 //just for debugging
            MessageBox.Show("start =" + index + " end =" + endIndex + " " + got.Text);

            got.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Blue));
            index =endIndex+1;
        }

第一个词是彩色的。但接下来的单词不是(即,如果文本是“去学校,我会去市场”,要搜索单词“去”,并且我按下搜索按钮,结果将是为第一个“go”着色,但第二个“go”不会着色)。

我估计出现这种情况是因为textRange工作不正常,或者TextPointer出了问题。此外,index 和 endIndex 是正确的 - 我已经测试过它们。

我感谢您的帮助。


试试这个代码:

 TextRange rangeText = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
 rangeText.Text = "Text1 ";
 rangeText.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
 rangeText.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);

 TextRange rangeWord = new TextRange(richTextBox.Document.ContentEnd,        richTextBox.Document.ContentEnd);
 rangeWord.Text = "word ";
 rangeWord.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
 rangeWord.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Regular);

 TextRange rangeTextOne = new TextRange(richTextBox.Document.ContentEnd,     richTextBox.Document.ContentEnd);
 rangeTextOne.Text = "Text2 ";
 rangeTextOne.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
 rangeTextOne.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# WPF 中的 TextRange 和 RichTextBox 的相关文章

随机推荐

  • Python 中的线程需要更长的时间而不是使其更快?

    我编写了 3 个不同的代码来比较有线程和没有线程 基本上测量通过使用线程节省了多少时间 结果没有任何意义 这是我的代码 import time def Function global x x 0 while x lt 300000000 x
  • 在多宿主 Windows 10 计算机上接收 UDP 多播消息

    我有一个C NET侦听 UDP 多播消息的客户端 我需要在单个网络接口上接收消息 有时我看不到收到的消息 当我禁用其他接口时 它可以工作 我尝试使用本网站上类似问题的代码将套接字选项设置为特定接口 但是 我不确定这是否只影响发送多播消息而不
  • 在 PHP 中学习 mvc 的最佳方法是什么? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我对 mvc 完全陌生 如何学习 走这条路 了解 MVC Google 一下 参见维基百科文章 选择一个框架 我建议 CodeIgni
  • 提高 Fortran 代码性能的提示和技巧 [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 如何在新的 iTunes connect 中创建应用内购买测试用户?

    我在 itune connect 中创建了一个测试用户 用户创建成功 并且还可以登录手机苹果商店 但是 当我要在同一用户的应用程序购买中进行测试时 我无法进行测试 总是显示错误 无法找到您输入的 Apple ID 或您的密码不正确 请重试
  • 适用于 Chrome,但不适用于 Firefox - jquery

    carat weight right li css left function index value if value 100 this children span css margin left 58px text align righ
  • 继续出现此编译错误[关闭]

    Closed 这个问题是无法重现或由拼写错误引起 help closed questions 目前不接受答案 当我编译时 我不断收到此错误 mario c 4 1 error expected identifier or 我尝试过改变一些东
  • .htaccess - 将域/lang/重定向到每种语言的子域

    我已经为此苦苦挣扎了好几个星期 但无法找到解决方案 我必须在多语言网站的 htaccess 中进行重定向 其所有页面都遵循相同的结构 但每种语言都有一个子域 以下方式对 http 和 https 有效 domain es es allpag
  • gcc -D_FORTIFY_SOURCE=1 和 -D_FORTIFY_SOURCE=2 之间的区别

    有人可以指出两者之间的区别吗gcc D FORTIFY SOURCE 1 and D FORTIFY SOURCE 2 我猜 2更安全吗 我无法找到逐点列出差异的列表 我也读过 D FORTIFY SOURCE 2应该与使用 O2 否则并非
  • 如何从 Scala 方法创建 UDF(计算 md5)?

    我想从两个已经工作的函数构建一个 UDF 我正在尝试计算 md5 哈希作为现有 Spark Dataframe 的新列 def md5 s String String toHex MessageDigest getInstance MD5
  • JavaScript 字符串按正则表达式结果分割子字符串包含空切片

    我有以下字符串分割 JavaScript 代码 var formula field1 field2 field5 field2 field3 console log formula split 而结果却出乎意料 field1 field2
  • QFileSystemModel rowCount 未按预期工作

    我正在尝试模型 视图编程中的一个示例 http doc qt io qt 5 model view programming html http doc qt io qt 5 model view programming html 为了演示如
  • 如何确定docker容器端口号?

    ASP NET 应用程序部署到 Docker 容器 即 可以通过以下方式访问 http 10 98 1 191 1673 webapp start http 10 98 1 191 1673 webapp start 从后端来看 我需要确定
  • 如何使用多个输入的任何循环指定输入目录?

    public class MultiXslt public static void main String args throws TransformerException ParserConfigurationException SAXE
  • 手机上的 Silverlight 网站

    我正在开发一个 Silverlight 网站 功能要求之一是旋转图像在所有浏览器上显示 该测试站点在所有桌面计算机浏览器中看起来都很棒 现在的问题是手机上的系统无法加载 我无法理解 iPhone 黑莓等设备上没有插件 但我的问题是在 Mic
  • PyScripter Rpyc

    也许有人可以给我一些如何将 Rpyc 安装到 PyScripter 的指南 我使用 PyScripter 1 9 9 7 和 Python 2 6 我尝试用谷歌搜索并找到一些说明 但仍然没有成功 Thanks 抓取文件rpyc 2 60 p
  • 如何获取树视图中的所有展开节点?

    我有一个包含 TreeView 的程序 除了根节点和根节点下的两个节点之外 我的所有节点都是从数据库加载的 当用户将数据添加到数据库时 它必须自动添加到 TreeView 我可以通过清除所有节点 添加默认节点并将所有数据 包括新节点 添加到
  • 意外的状态行:ICY 200 对于 URL openStream() 方法可以吗?

    根据 kitakt 4 4 的更改 播放 Shoutcast 流会出现一些问题 那些返回 ICY 而不是 HTTP 1 x 响应的问题 因此 kitkat 的解决方案是在我们打开流之前在 JVM 中重新注册一次 icy 协议前缀 try j
  • OCaml 中的“[< >]”是什么意思?

    我看过一些源代码 let rec parse document parser lt len parse int32 st gt gt parse list ES take int32 len st lt gt gt malformed pa
  • C# WPF 中的 TextRange 和 RichTextBox

    我一直在尝试编写一个程序来在 richTextBox 中搜索单词 我已经完成了大部分 但看起来我错过了一些东西 我想为找到的单词着色 所以我写了以下内容 private void button1 Click object sender Ro