Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CollectionViewSource does not re-sort on property change

I'm binding ItemsControl to CollectionViewSource. Here is code:

this.Trucks = new ObservableCollection<Truck>();
            foreach (var truck in DataRepository.Trucks.Where(t => t.ReadyDate.Date.Equals(this.Date)))
            {
                this.Trucks.Add(truck);
            }

            this.TrucksSource = new CollectionViewSource { Source = this.Trucks };
            this.TrucksSource.SortDescriptions.Add(new SortDescription("ReadyAddress.Region.RegionNumber", ListSortDirection.Ascending));
            this.TrucksSource.SortDescriptions.Add(new SortDescription("TruckId", ListSortDirection.Ascending));

When I initially bind - sorting works. When I add item to ObservableCollection - it is inserted in proper spot, thats good. But when I change property which I sort by - this item is not being "shifted" in a list.

ReadyAddress.Region.RegionNumber properly raises INotifyPropertyChanged and I see it in bound fields, but order does not change. Do I expect something that shouldn't happen or there is better way to handle this?

like image 952
katit Avatar asked Jun 30 '12 02:06

katit


1 Answers

Late answer, but with 4.5 the ListCollectionView (the default implementation for a ListBox and CollectionViewSource.View) new properties were added to make this possible.

You can use the IsListSorting and ListSortingProperties to enable automatic resorting. And no, it does not rebuild the view

list.SortDescriptions.Add(new SortDescription("MyProperty", ListSortDirection.Ascending));
list.IsLiveSorting = true;
list.LiveSortingProperties.Add("MyProperty");

This should resort when the property MyProperty changes.

like image 181
Shawn Kendrot Avatar answered Sep 21 '22 14:09

Shawn Kendrot