I have a scenario where in I populate a listbox with a 1000 items. I set the ItemsSource property with a source of data.
I have a requirement where I need to strike out an item of the listbox based on certain criteria, when the UI loads. I am using styles + attached properties to achieve the same by setting ContentTemplate of ListBoxItem in the callback method of attached property.
My problem is when I try to generate a ListBoxItem using ItemContainerGenerator.ContainerFromItem, for an item which is at the end of the list, I get null. As a result, I cannot strike out items of the listbox which are at the bottom of the list.
Has it got something to do with virtualization. I want to obtain all those ListBoxItems on load.
Is there any workaround?
Thanks
This is definitely caused by virtualization. This is exactly what UI virtualization is supposed to do - only create
ListBoxItemobjects for items that are visible on the screen. You can easily see that this is indeed the cause by settingVirtualizingStackPanel.IsVirtualizing = falseon yourListBoxand see thatItemContainerGenerator.ContainerFromItemno longer returnsnull.You can set a style for your
ListBoxItemsin yourListBoxthat will have the logic to strike out the items as needed. This should also work when virtualization is enabled. For example: