开发者

Highlight a word in a silverlight textblock

开发者 https://www.devze.com 2023-02-11 06:39 出处:网络
I need a way to high开发者_JAVA技巧light a text in a silverlight textblock or textbox. This is for highlighting search results like if you try to Ctrl+F in your browser and search for a word, the brow

I need a way to high开发者_JAVA技巧light a text in a silverlight textblock or textbox. This is for highlighting search results like if you try to Ctrl+F in your browser and search for a word, the browser will highlight the matched words.


In a textblock you can use a Run to highlight words, for example:-

  <TextBlock>Ordinary Text&#160;<Run Foreground="Red">Highlighted Text</Run>&#160;More Ordinary Text</TextBlock>

Note the use of the Xml character entity &#160 which is the non-breaking space, which is necessary because Xaml parsing (as result of its reliance on XML parsing) means the white space directly before a < and white space directly after a > is ignored.


I've had a similar problem and found this question in Silverlight forum. Maybe it could help you.

How to Highlight a particular WRONG word in Textbox to make SpellCheck feature

This is how I would implement the search function:

private void Find(RichTextBox richTextBox, string term)
{
    var builder = new StringBuilder();

    var inlines = richTextBox.Blocks
        .OfType<Paragraph>()
        .SelectMany(paragraph => paragraph.Inlines);

    foreach( var inline in inlines )
    {
        builder.Append(((Run)inline).Text);
    }

    var regex = new Regex(term);
    var matchedStrings = regex.Matches(builder.ToString());
    foreach( var item in matchedStrings )
    {
        // Whatever you want to do.
    }
}
0

精彩评论

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

关注公众号