WPF DataGrid ignores SortDescription

Hendrik Wiese picture Hendrik Wiese · Jun 24, 2012 · Viewed 7.7k times · Source

I've got a strange problem here regarding sorting of a WPF DataGrid (System.Windows.Controls.DataGrid in .NET 4.0).

Its ItemsSource is bound to a property of the datacontext object:

<DataGrid HeadersVisibility="Column" SelectedIndex="0" MinHeight="30" ItemsSource="{Binding FahrtenView}" AutoGenerateColumns="False" x:Name="fahrtenDG">

FahrtenView looks like this:

    public ICollectionView FahrtenView
    {
        get
        {
            var view = CollectionViewSource.GetDefaultView(_fahrten);
            view.SortDescriptions.Add(new SortDescription("Index", ListSortDirection.Ascending));
            return view;
        }
    }

The DataGrid gets sorted. However it only gets sorted the very first time it's assigned a DataContext. After that, changing the DataContext (by selecting another "parental" object in a data hierarchy) still causes the property FahrtenView to be evaluated (I can put a BP in and debugger stops there) but the added sortdescription is completely ignored, hence sorting does not work anymore.

Even calling fahrtenDG.Items.Refresh() on every DataContextChange doesn't help.

I'm pretty sure this is the way to go when it comes to sorting a WPF DataGrid, isn't it? So why does it refuse to work so obstinately after doing its job perfectly the very first time it gets called?

Any idea? I'd be very grateful.

Cheers, Hendrik

Answer

Hendrik Wiese picture Hendrik Wiese · Aug 6, 2012

I've inherited from DataGrid to catch a brief glimpse on its guts. What I've found is that for some mysterious reasons, although the first time OnItemsSourceChanged gets called, everything looks fine, in every following call of OnItemsSourceChanged the SortDescription list of the ItemsSource collection view is empty.

For that reason I've added a custom SetupSortDescription event that is called at the end of OnItemsSourceChanged. Now I'm adding the sort descriptions in the event handler function, which's working like a charm.

I consider this a bug in the WPF toolkit DataGrid.

Here's my overridden OnItemsSourceChanged

    protected override void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
    {
        if (SetupSortDescriptions != null && (newValue != null)) 
            SetupSortDescriptions(this, new ValueEventArgs<CollectionView>((CollectionView)newValue)); 

        base.OnItemsSourceChanged(oldValue, newValue);
    }