ListBox ItemContainerGenerator returns null even when listbox has items

折月煮酒 提交于 2020-01-02 05:58:13

问题


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.



来源:https://stackoverflow.com/questions/5729079/listbox-itemcontainergenerator-returns-null-even-when-listbox-has-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!