Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF ListBox displays duplicate items. How to get around?

I have a ListBox with a nested ListBox inside. Both have ObservableCollections as their ItemsSource set with the inner ListBox's collection being a member of the outer one's Objects...

The collections are filled by a BackgroundWorker which gathers data from a webservice. I had to change from ObservableCollection to an AsyncObservableCollection in order to be able to add items from within the worker's code. AsyncObservableCollection code is from here: Have worker thread update ObservableCollection that is bound to a ListCollectionView

My problem is that the inner ListBox keeps to display duplicate items. It seems as if it always duplicates the first item if it decides to duplicate. I have no clue why this happens. With an event listener attached to the CollectionChanged event of the collection I found out that the event is being fired fine once per item.

Do you have any ideas?

Thanks, Stephan

like image 558
sjanz Avatar asked Nov 26 '22 10:11

sjanz


1 Answers

If you bind your ItemsSource to an AsyncObservableCollection, you must using a VistualizingStackPanel to correct this problem :

<ListBox
 ItemTemplate="{StaticResource YourItemTemplate}"
 ItemsSource="{Binding Path=YourAsyncObservableCollection}" 
 ScrollViewer.CanContentScroll="False"
 ScrollViewer.HorizontalScrollBarVisibility="Auto"
 ScrollViewer.VerticalScrollBarVisibility="Disabled"
 Style="{DynamicResource YourListBoxStyle}">
 <ListBox.ItemsPanel>
  <ItemsPanelTemplate>
   <VirtualizingStackPanel Orientation="Vertical" />
  </ItemsPanelTemplate>
 </ListBox.ItemsPanel>
</ListBox>
like image 61
ChimouRabane Avatar answered Dec 15 '22 08:12

ChimouRabane