ListBox ItemContainerGenerator returns null even w

2019-05-06 23:17发布

问题:

I've a listbox with couple of items, till the time no scrollbar appears everything goes perfectly fine but once scrollbar comes then ItemContainerGenerator returns null.

I read some blogs and found it may be because of vertualization stackpanel. If i disable that then it may work but in my case it would make listbox too much heavy and less efficient.

Here is the code for listbox:

 <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 listbox element. I verified that itemsControl is correct and it has items when firstContainer is null.

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

One more quite noticing thing: I saw there're 8 listbox items in ItemsControl. ItemContainerGenerator status says *Container Generated *

No idea why it's not returning ItemsContainer Thoughts ??

回答1:

Virtualization means that listboxitems only gets generated if visible. So you can not use the ItemContainerGenerator to get non generated (non visible) listbox items.

Do you really need the listbox item directly? It looks like your listbox is data driven so work with the data directly.