Maxim Mamedov
Maxim Mamedov

Reputation: 49

WPF. Group items in ListBox without ItemsSource

I add items to ListBox like this;

tvProgramListBox.Items.Add(r);

And after adding all objects I'm trying to group items like this;

CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(tvProgramListBox.Items);
PropertyGroupDescription groupDescription = new PropertyGroupDescription("date");
view.GroupDescriptions.Clear();
view.GroupDescriptions.Add(groupDescription);

or like this;

PropertyGroupDescription groupDescription = new PropertyGroupDescription("date");
tvProgramListBox.Items.GroupDescriptions.Clear();
tvProgramListBox.Items.GroupDescriptions.Add(groupDescription);

date property exists in items. However, ListBox does not group items. When I used ItemsSource binding before, grouping was working. But there is many items in my collection and I decided to add them manually to ListBox in the background thread to keep UI free from freezes. So now it doesn't freeze, but doesn't group either :) Any suggestions appreciated. Thanks.

Upvotes: 2

Views: 527

Answers (1)

Sean Beanland
Sean Beanland

Reputation: 1118

If you want to add items to your collection in a background thread but still use ItemsSource you can use BindingOperations.EnableCollectionSynchronization to do so.

Add this using statement:

using System.Windows.Data;

You'll need an object for the binding engine to lock on in addition to your collection:

ObservableCollection<MyType> Source = new ObservableCollection<MyType>();
object myLock = new object();

Now you can enable the synchronization where appropriate.

BindingOperations.EnableCollectionSynchronization(Source, myLock);

You should now be able to update the collection from a background thread while still using ItemsSource on the ListBox.

Upvotes: 1

Related Questions