c# - 搜索 RichTextBox 并突出显示该特定单词的所有实例的方法

标签 c# wpf richtextbox flowdocument

我真的不知道应该从哪里开始。

我有一个带有 RichTextBox 的 WPF 应用程序,其中包含使用 FlowDocument 的文本负载,该文本会根据用户的选择而变化。

我需要一种方法,用户可以通过该方法在 TextBox 中输入单词,并且如果找到该单词的每个实例,则将在相邻的 RichTextBox 中突出显示>。 http://kentb.blogspot.com/2009/06/search-and-highlight-text-in-arbitrary.html这个想法很完美,但我对如何使用 RichTextBox 将其应用到我的应用程序一无所知。

提前谢谢您!

最佳答案

您尝试过使用正则表达式吗?

类似于:

private void searchButton_Click(object sender, EventArgs e)
{
    //Select all text and bring it back to default color values so you
    //can make a new search selection

    richTextBox1.SelectAll();
    richTextBox1.SelectionColor = System.Drawing.Colors.Black;

    //Deselect all text to ready selections

    richTextBox1.DeselectAll();

    //Create a MatchList variable and initialize it to all matches
    //within the RichTextBox. Add a using statement of 
    //System.Text.RegularExpressions 

    Color evenColor = Color.Red;
    Color oddColor = Color.Blue;

    MatchCollection matches = Regex.Matches(richTextBox1.Text,  searchTextBox.Text);

    //Apply color to all matching text
    int matchCount = 0;
    foreach (Match match in matches)
    {
        richTextBox1.Select(match.Index, match.Length);
        //richTextBox1.SelectionColor = System.Drawing.Color.Red;
        richTextBox1.SelectionColor = 
            matchCount++ % 2 == 0 ? evenColor : oddColor;
    }
}

只要您的盒子中不需要同时使用多种颜色,此方法就有效。我相信,通过一些额外的逻辑,您也可以将其纳入其中。

编辑:在 WPF 中不起作用。持续关注 WinForms。

关于c# - 搜索 RichTextBox 并突出显示该特定单词的所有实例的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8772308/

相关文章:

c# - 如何使用组合框更改 richTextBox 字体大小

c# - WPF RichTextBox 拼写检查 ComException

c# - 值不能为空。参数名称: baseUri

C#.NET : How to choose which Network adapter to connect my Application at runtime

.net - 显示带有描述的对话框

.net - Awesomium WebControl 挂起

c# - 如果其中一个 subview 的值在 Windows 8.1 应用程序中更新,如何更新父 ViewModel 中的值

c# - 如何在 Unity3d、C# 中按下按键时播放 AnimationClip?

c# - 如何将解决方案测试的代码覆盖率结果文件输出到解决方案目录而不是测试项目目录

.net - 使用.net RichTextEdit,但过滤数据类型?