I have a TextBox and ListBox. User can search ListBox elements from TextBox.
ListBox is bound to CollectionViewSource.
CollectionViewSource has Filter event handler, that filters elements based on text that user enters into TextBox.
My requirement is to highlight user entered text within TextBlock of ListBoxItem elements.
I was thinking of breaking TextBlock into several Runs objects and modify Background property of Run objects that need to be highlighted.
I think it is not possible to do with DataTemplates.
Is there easy way to accomplish this?
Thank You!
Best Solution
UPDATE: I have elaborated significantly on this subject in this blog post.
I don't think there's any easy way to do this, but here is how I would tackle this problem:
Background
of theTextBlock
s to the indexes. Use a converter to convert the indexes into aGradientBrush
that is bright yellow (or whatever) between the two indexes.Here's how I think you can figure out the dimensions of the highlighted portions of the
TextBlock
:TextPointer
via theTextBlock.ContentStart
property.TextPointer.GetPositionAtOffset(indexOfStart)
usingLogicalDirection.Forwards
.TextPointer.GetPositionAtOffset(indexOfStart)
usingLogicalDirection.Backwards
.TextPointer.GetCharacterRect
to get the boundingRectangle
of the highlighted content.To be honest, I'm not sure that last bit work. I'd have to try it for myself, and I may do that for a blog post.
EDIT: Just had time to try this for myself. It definitely works, although with slight changes to my logic above. Below is the code that demonstrates. Here is a screenshot:
Screenshot http://img219.imageshack.us/img219/2969/searchx.png
Window1.xaml:
Window1.xaml.cs:
I think the code is fairly self-explanatory. Obviously you will need to extend the concept to your particular scenario. You may prefer to leverage the
Background
property of theTextBlock
combined with aDrawingBrush
orGradientBrush
instead of having the separatePath
.