I'm trying to highlight part of text in a textblock from a listbox datatemplate which in turn is bounded to a property of a custom class by using a textbox to search the list for input text.
But the problem is that only part of the items are highlighting (most of the ones visible) but when i maximize the window and try to input another character then suddenly all of them gets highlighted my guess where the problem might be is in this piece of code:
ListBoxItem listboxItemFound= (ListBoxItem)this.listBox1.ItemContainerGenerator.ContainerFromItem(TItem);
Since this method is returning a null when the items are not visible but the items are currently in the listbox.
Somehow I guess the items listboxItem instances are not yet created until you scroll down or maximize to view more items.
XAML DataTemplate:
<DataTemplate>
<Grid Name="gridOfListbox" Height="25" Margin="0,2">
<DockPanel Name="dockpanelWithTxtBlock">
<TextBlock Name="textbloxk" DockPanel.Dock="Left" FontSize="15" TextAlignment="Center">
<Run Text="" /><Run Background="Yellow" Text="" /><Run Text="{Binding ProductID}" />
</TextBlock>
</DockPanel>
</Grid>
</DataTemplate>
If more code is needed just let me know.
Any help would be greatly appreciated!!
Also if there is any other better way of finding the listboxItem bounded to the custom Item just let me know. Thank you very much!
[Pic of problem] https://i.stack.imgur.com/HViag.png
One way to fix this is to set VirtualizingStackPanel.IsVirtualizing to
falsefor yourListBox. This will cause all of the items to be created right away. The downside to this is if yourListBoxhas many items, your program will use more memory (since more items will be created), and could potentially run slower depending on the number of items.A better solution to consider would be to have multiple
DataTemplates for this - one without the highlight, and one with. You can set a DataTemplateSelector for yourListBox(using the ItemTemplateSelector property). The selector can choose which template to use based on if the item matches the search term or not.The tricky part would be writing the template with the highlighted text. You could probably achieve that by having properties on the object the
ListBoxItemis bound to for the text before the highlighted text, the highlighted text, and then the remaining text.