Wednesday, February 2, 2011

How to Properly Sort on a WPF DataGrid Column in Code

There are a lot of blog posts and articles out there on how to apply a sort to a datagrid in code, but there are very few out there that show you how to do it properly. Most of the posts I ran into show you how to apply the sort, but the column header does not update properly. The items are sorted, but the sort indicator (tiny triangle on the header)

image

Does not appear. This can be really confusing especially if you have already sorted by another column by clicking on the column header. This makes the sort indicator appear on that column, but if you sort by a different one in the code behind, the sort indicator still shows that the grid is sorted by the first column (Thanks WPF DataGrid! Nice one!)

Well, there is a way to get it working properly. Here it is.

        private void applySortDescriptions(DataGridColumn col, ListSortDirection listSortDirection)
        {
            //Clear current sort descriptions
            MyDataGrid.Items.SortDescriptions.Clear();

            //Get property name to apply sort based on desired column
            string propertyName = getSortPropertyName(col);           

            //Add the new sort description
            MyDataGrid.Items.SortDescriptions.Add(new SortDescription(propertyName, listSortDirection));
           
            //apply sort
            applySortDirection(col, listSortDirection);           
           
            //refresh items to display sort
            MyDataGrid.Items.Refresh();
        }

        private string getSortPropertyName(DataGridColumn col)
        {
            //place logic in here that will return the name of the property to sort by (ex: return “name”; if you are sorting by the name property)

            return string.Empty;
        }

        private void applySortDirection(DataGridColumn col, ListSortDirection listSortDirection)
        {
            foreach (DataGridColumn c in PatientsViewDatGrid.Columns)
            {
                c.SortDirection = null;
            }
            col.SortDirection = listSortDirection;
        }

That should do it. Now you can sort and the column headers will show the sort indicator appropriately.