datagrid sorting at startup and codebehind.

Apr 16, 2009 at 10:15 PM
Edited Apr 16, 2009 at 10:29 PM
I'm using the DataGrid to visualize my list of items, however I can't find how to sort the list by a specific column in several places in my design at runtime. Maybe someone can help me with the C# for this. I would like to:
1.) Sort on a specific column on start up of the application. (If the user doesn't click a header to sort by, all new items go to the bottom)
2.) From code behind, just sort on a column  in some order.

Thanks
/J
Apr 17, 2009 at 1:04 AM
I figured out the whole ICollectionView on which you actually apply the sorts.

I have a timer that starts on Loaded of by DataGrid. Every interval it checks to see if ItemsSource isn't null, and if it isn't start my "real" Loaded handler called Initialize();

      void Initialize()
      {
         ICollectionView view = CollectionViewSource.GetDefaultView(this.ItemsSource);
         view.SortDescriptions.Clear();
         view.SortDescriptions.Add(new SortDescription("Foo.bar", ListSortDirection.Descending));
         view.Refresh();
      }