开发者

How can I highlight, not select, text in a data bound WPF TextBox or RichTextBox?

Some context: I'm trying to highlight all occurrences of some searched text in a data bound TextBox or a 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>

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));
     }

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜