Skip to content

Unable to sort trackable collection in DataGrid. #45

Description

@ericdc66

Normally, a WPF DataGrid will sort a collection by clicking on column headers. If I apply AsTrackable() to the collection, then sorting no longer works. The sort indicators on the column header still shows the direction of the sort, but the rows do not change to show the sort order.

Here's an example:

MainWindow.xaml:

<Window x:Class="ChangeTrackingTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
    <DataGrid CanUserAddRows="False" CanUserSortColumns="True" AutoGenerateColumns="False" ItemsSource="{Binding TestData}">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Name}" CanUserSort="True" Header="Name"/>
            <DataGridTextColumn Binding="{Binding Desc}" CanUserSort="True" Header="Description"/>
        </DataGrid.Columns>
    </DataGrid>
</Window>

MainWindow.xaml.cs:

using System.Collections.Generic;
using System.Windows;
using ChangeTracking;

namespace ChangeTrackingTest
{
    public class Data
    {
        public virtual string Name { get; set; }
        public virtual string Desc { get; set; }

        public Data() { }

        public Data(string name, string desc)
        {
            Name = name;
            Desc = desc;
        }
    }

    public class ViewModel
    {
        public IList<Data> TestData { get; set; }

        public ViewModel(IList<Data> data)
        {
            TestData = data;
        }
    }

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            //var data = GetData(); // This sorts but isn't Trackable
            var data = GetData().AsTrackable(); // This is Trackable but won't sort

            var viewModel = new ViewModel(data);
            DataContext = viewModel;

            InitializeComponent();
        }

        private static IList<Data> GetData()
        {
            return new List<Data>()
            {
                new Data("Train", "My train"),
                new Data("Car", "My car"),
                new Data("Plane", "My plane")
            };
        }
    }
}

Switch the comments on the var data statements in the MainWindow constructor to see that it is just AsTrackable() that breaks sorting.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions