Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind to a sorted ObservableCollection<T> in a ListBox

I have a list of data objects in my Windows Phone 7 application called MyObjectList, which inherits ObservableCollection<MyObject>. I keep the list in memory in a public property of App called MyObjects. My goal is to bind the data to a ListBox and have it sorted by MyObject.Name.

Currently, I have a ListBox in XAML with the name MyObjectsList and the following code in the constructor to link it up:

public MyObjectListView()
{
    InitializeComponent();
    this.MyObjectsList.ItemsSource = ((App)App.Current).MyObjects;
}

This works great. I add items to MyObjects and they show up in the ListBox. However, the data isn't sorted by name when it appears in the list. I tried the following change to get the data to be sorted:

this.MyObjectsList.ItemsSource = ((App)App.Current).MyObjects
                                         .OrderBy(x => x.Name)

But when I do that, I don't see any objects reflected in the ListBox sorted or otherwise.

What can I do so that when I add an item to my ObservableCollection, it shows up sorted by .Name in the ListBox?

like image 304
Ben McCormack Avatar asked Aug 24 '10 02:08

Ben McCormack


3 Answers

You could use a sorted collection instead of your standard ObservableCollection. Someone wrote a SortedObservableCollection here:

http://phillters.wordpress.com/2009/05/14/sortedobservablecollection/

like image 45
Timwi Avatar answered Nov 08 '22 05:11

Timwi


The problem with your example is the OrderBy method returns an IOrderedEnumerable type of object instead of an ObservableCollection.

Here's something you can do without implementing a custom collection like some of the other answers.

var sortedMyObjects = new ObservableCollection<MyObject>();
foreach (var myobj in ((App)App.Current).MyObjects.Orderby(x => x.Name))
    sortedMyObjects.Add(myobj);
this.MyObjectsList.ItemsSource = sortedMyObjects;

The other answers all suggest viable alternatives, but this will solve the problem in the question.

FWIW, in Silverlight 4 there is a PagedCollectionView, but Windows Phone 7's Silverlight is based on Silverlight 3 and that isn't available. I'm only mentioning this to keep you aware of it in anticipation of WP7 eventually updating to SL4.

like image 174
Matt Casto Avatar answered Nov 08 '22 05:11

Matt Casto


This doesn't help you for Silverlight, but for WPF 3.5/4, there's a better way to do this involving CollectionView

like image 1
Ana Betts Avatar answered Nov 08 '22 05:11

Ana Betts