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?
All answers I found mentioned
View.Refresh()but that’s not very good solution for big lists. What I ended up doing was toRemove()andAdd()this item. Then it was properly repositioned without reloading whole list.Word of caution! It works for what I do, but in your case removing object and re-adding may cause side effect depending how your code written. In my case it’s a list with UI effect where new items show up with transition so refreshing will show transition on whole list where remove/add nicely shows how item get’s repositioned.