Reputation: 2913
I need a way to highlight 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.
Upvotes: 3
Views: 2696
Reputation: 6948
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.
}
}
Upvotes: 0
Reputation: 189457
In a textblock you can use a Run
to highlight words, for example:-
<TextBlock>Ordinary Text <Run Foreground="Red">Highlighted Text</Run> More Ordinary Text</TextBlock>
Note the use of the Xml character entity  
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.
Upvotes: 2