The observable collection doesn't implement sorting, for the simple reason that every time an item moves from one location in the list to another the collection raises an event. That would be great for watching animations of the sort algorithm in action, but it would sort of suck for, you know, sorting.
There are two ways to do this; they're very similar, and both start by sorting the items outside their observable collection, e.g. if _Fruits
is an ObservableCollection<Fruit>
, and you've defined an IComparer<Fruit>
for the sort, you'd do:
var sorted = _Fruits.OrderBy(x => x, new FruitComparer());
That creates a new IEnumerable<Fruit>
that, when you iterate over it, will have the objects in the new order. There are two things you can do with this.
One is to create a new collection, replace the old one, and force any items control(s) in the UI to rebind to it:
_Fruits = new ObservableCollection<Fruit>(sorted);
OnPropertyChanged("Fruits");
(This assumes that your class implements INotifyPropertyChanged
in the usual way.)
The other is to create a new sorted list, and then use it to move the items in your collection:
int i = 0;
foreach (Fruit f in sorted)
{
_Fruits.MoveItem(_Fruits.IndexOf(f), i);
i++;
}
The second approach is something I'd only try if I had a really serious commitment to not rebinding the items controls, because it's going to raise a ton of collection-changed events.