[Silverlight 2, C#] Datagrid Not Sorting?
So I’ve been playing around with Siverlight datagrids. I have an xml page stuffed with data which I read into a custom class I made to store an xml node and it’s properties… I then databind a List of myClass to the datagrid itemsource and everything works fine – sorting worked fine right out of the box.
But then I decided to add my own context filtering to my grid, where the datagrid source is filtered based on input from the user in a textbox. I used a LINQ query on the List of myClass to do my filtering and when I databound the result of my LINQ query to my datagrid, BAM, the auto column sorting stopped working; the arrows on each of the columns just didn’t show up.
The Problem:
I was a little confused, but after a quick google search it appears that:
1. You must databind to a class that implements the IList interface [gives access to the Sort method] to get the auto sorting to work on a datagrid.
2. My LINQ query returns System.Collections.Generic.IEnumerable.
3. IEnumerable does NOT implement IList, but List does.
The Solution:
Use the ToList() function on the returned IEnumberable to create List of the results so that we DO have access to the Sort() method.
var filteredResults = from x in m_alarmList where (x.customProp.Contains(searchVal)) select x; _myDataGrid.ItemsSource = filteredResults.ToList();
Thanks to this post: For bringing the difference between IEnumberable and List to my attention.
Tags: datagrid, ienumerable, list, sorting

And another important part of List is that it implements ObservableCollection which the DataGrid loves (or at least likes as a friend)!