Highlight a word in a silverlight textblock
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 <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.
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.
}
}
加载中,请稍侯......
精彩评论