If you have a lot of text in part of your app, maybe even a grid with very text-oriented cell content, you may at some point want to implement a search feature that allows you to highlight where in you app certain search terms can be found.
In case you’re not with me, above is a screenshot of an app I created to illustrate this point.
The custom TextBlock that I have created is in the light blue area. As you can see, when you change the search term it changes the highlighting to reflect any matches. You also have a match count, that automatically updates when the search term or the text for the TextBlock changes.
Here is the XAML for the page I am using my new control.
As you can see, the control (local:HighlightingTextBlock) has its Text property and HighlightText property bound to the two test TextBoxes in the app. As the user types in either TextBox, the HighlightingTextBlock control updates the search hits and match count.
So, lets take a look at the control class to see where the magic happens:
And this is the control’s default Style and Template that is in Generic.xaml
As you would expect, there is a good amount of DependencyProperty code, as well as a method called ProcessTextChanged which is invoked whenever any of the input text or search text changes.
The key principle behind this solution, is that a TextBlock doesn’t necessarily have to only have a Text (string) property. TextBlock also has a collection on ‘InLines’, which are visual elements (typically ‘Runs’) that can each have individual styling – which allows us to ‘compose’ a TextBlock that has different styling at different points in the text string – which is exactly the result we are after.
Why not run this up for yourself ? You can download it from my GitHub account here
WPF HighlightSearchMatchTextBlock (GitHub)
What do you think, let me know your thoughts. Also, why not connect with me via my links on the right, or perhaps even subscribe to my updates.