ListBox ItemContainerGenerator returns null even if there are items in the list

I have a list with two elements, until no scrollbar appears, everything will be fine, but as soon as the scrollbar appears, ItemContainerGenerator will return null.

I read several blogs and found that this could be due to the vertical stack panel. If I turn this off then it might work, but in my case it will make the list too large and less efficient.

Here is the code for the list:

<ListBox x:Name="EventListBox" DockPanel.Dock="Top" Margin="5,5,5,5" FocusVisualStyle="{x:Null}" ItemsSource="{Binding EventModelViewCollectionView}" Style="{StaticResource DefaultListBoxStyle}" ItemTemplate="{StaticResource EventTemplate}" SelectedItem="{Binding EventModelViewCollection.SelectedItem}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.CanContentScroll="True" ScrollViewer.IsDeferredScrollingEnabled="False" ScrollViewer.ScrollChanged="EventScrollViewer_ScrollChanged" IsSynchronizedWithCurrentItem="True" Loaded="ListBox_Unloaded"> 

This returns null.

Here firstContainer should be the first element of the list. I checked that the itemsControl is correct and it has elements when firstContainer is null.

 DependencyObject firstContainer = itemsControl.ItemContainerGenerator.ContainerFromIndex(0); 

Another great thing: I saw that there are 8 list items in the ItemsControl. ItemContainerGenerator status says * Container created *

I don’t know why this does not return ItemsContainer Thoughts ??

+4
source share
1 answer

Virtualization means that listboxitems are only generated if visible. Thus, you cannot use ItemContainerGenerator to retrieve non-generated (invisible) list items.

Do you really need a list item directly? It looks like your list is data, so work with the data directly.

+4
source

All Articles