I have an observable collection which is binded to datagrid… I want to sort the datagrid by clicking on header. It’s a dynamic data. Here is my code
namespace SLSortObservableCollection
{
public partial class MainPage : UserControl
{
//ObservableCollection<int> NumData = new ObservableCollection<int>();
// ObservableCollection<string> StrData = new ObservableCollection<string>();
public MainPage()
{
InitializeComponent();
ObservableCollection<int> NumData = new ObservableCollection<int>();
ObservableCollection<string> StrData = new ObservableCollection<string>();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Random ra = new Random();
for (int i = 0; i < 10; i++)
{
int num = ra.Next(1000);
NumData.Add(num);
}
try
{
dataGrid1.ItemsSource = null;
dataGrid1.ItemsSource = NumData;
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
}
private void button2_Click(object sender, RoutedEventArgs e)
{
try
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < 5; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
StrData.Add(builder.ToString());
}
dataGrid1.ItemsSource = StrData;
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
}
}
}
ObservableCollection does not support sorting at all. If this was not silverlight, you might be able to do something with CollectionView.
As it is, you will probably have to use a custom extension of SortableCollection. There are several of these flying around, just search for “sortable observableCollection”
Some implementations to get you started
http://kiwigis.blogspot.de/2010/03/how-to-sort-obversablecollection.html
http://elegantcode.com/2009/05/14/write-a-sortable-observablecollection-for-wpf/
http://sortablecollection.codeplex.com/