如何突出显示而不是选择数据绑定的WPF TextBox或RichTextBox中的文本? [英] How can I highlight, not select, text in a data bound WPF TextBox or RichTextBox?

查看:68
本文介绍了如何突出显示而不是选择数据绑定的WPF TextBox或RichTextBox中的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

某些情况:我试图突出显示在数据绑定的TextBox或RichTextBox中出现的某些搜索文本.

Some context: I'm trying to highlight all occurrences of some searched text in a data bound TextBox or a RichTextBox.

到目前为止我所发现的:我想出了如何突出显示RichTextBox中的文本:

What I have found until now: I figured out how to highlight text in a RichTextBox:

    <RichTextBox>
        <FlowDocument>
            <Paragraph>
                <Run>In this</Run>
                <Run Background="Yellow">example</Run>
                <Run>the word</Run>
                <Run Background="Yellow">example</Run>
                <Run>is highlighted.</Run>
            </Paragraph>
        </FlowDocument>
    </RichTextBox>

问题:例如,如何使用某些IValueConverter绑定此RichTextBox,以便突出显示所有出现的"example"表达式?

Question: How can I, for example, by using some IValueConverter, bind this RichTextBox so that all occurrences of the expression "example" are highlighted?

推荐答案

     string example = "example";
     string exampleDoc = "hello, example, hello example.";
     FlowDocument doc =
        new FlowDocument(new Paragraph(new Run("hello, example, hello example.")));
     int pos = 0;
     while (0 <= (pos = exampleDoc.IndexOf(example)))
     {
        new Bold(doc.ContentStart.GetPositionAtOffset(pos),
                 doc.ContentStart.GetPositionAtOffset(pos + example.Length));
     }

这将使您入门.通过将要突出显示的单词的ConverterParameter将其放在从字符串到FlowDocument的ValueConverter中是很容易的.当您添加更多格式时,请注意TextPointer的更改,您将看到突出显示向左移动.我相信您会找出适合您情况的最佳方法.

This will get you started. It would be easy to put this in a ValueConverter from string to FlowDocument with a ConverterParameter of the word you want to highlight. Watch out for the TextPointer changing as you add more formats, you'll see the highlighting shift to the left. I'm sure you'll figure out the best way to handle this in your situation.

这篇关于如何突出显示而不是选择数据绑定的WPF TextBox或RichTextBox中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆