Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

WPF DataGrid: Enable standard sorting of nullable types on autogenerated columns

0.00/5 (No votes)
14 Oct 2013 1  
DataGrid does not sort a nullable value type on an autogenerated column.

Introduction

It's quite common to bind a WPF DataGrid to data using autogenerated columns. It's equally common to have bound properties of a nullable type (ie  Nullable<int>) . However DataGrid does not provide the standard sorting behaviour for nullable types, the column header is not highlighted and clicking has no action. 

Background  

The culprit is the DataGridColumn.CreateDefaultColumn(ItemPropertyInfo) method: It tests the bound property type for IComparable, int inherits from IComparable, but not int? and therefore DataGridColumn .CanUserSort is set to false. 

Using the code 

The remedy is simple, attach this handler to the DataGrid.AutoGeneratingColumn event: 

void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (!e.Column.CanUserSort)
    {
        Type type = e.PropertyType;
        if (type.IsGenericType && type.IsValueType && typeof(IComparable).IsAssignableFrom(type.GetGenericArguments()[0]))
        {
            // allow nullable primitives to be sorted
            Debug.Assert(type.Name == "Nullable`1");
            e.Column.CanUserSort = true;
        }
    }
} 
 


License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here