Событие пожарной сортировки WPF в коде - PullRequest
0 голосов
/ 27 августа 2018

У меня есть код, который прослушивает событие "сортировки" сетки данных, чтобы иметь возможность добавить пользовательский сортировщик ...

Я добавляю это, когда сетка данных загружена.

grid.Sorting += (sender, args) =>
            {
                var column = (DataGridCustomTextColumn) args.Column;



                //i do some custom checking based on column to get the right comparer
                //i have different comparers for different columns. I also handle the sort direction
                //in my comparer

                // prevent the built-in sort from sorting
                args.Handled = true;

                var direction = (column.SortDirection != ListSortDirection.Ascending)
                    ? ListSortDirection.Ascending
                    : ListSortDirection.Descending;

                //set the sort order on the column
                column.SortDirection = direction;

                //use a ListCollectionView to do the sort.
                var lcv = (ListCollectionView) CollectionViewSource.GetDefaultView(grid.ItemsSource);

                //this is my custom sorter it just derives from IComparer and has a few properties
                //you could just apply the comparer but i needed to do a few extra bits and pieces
                var comparer = new DataGridCommonSort(column.RealDataType, column.SortMemberPath, direction);

                //apply the sort
                lcv.CustomSort = comparer;

            };

Проблема в том, что этот обработчик вызывается только когда я щелкаю заголовок столбца. Но мне нужен способ инициировать это событие, когда данные сортируются

Есть идеи? Я пробовал что-то вроде:

ICollectionView dataView = CollectionViewSource.GetDefaultView(dataGrid.ItemsSource);
            dataView.SortDescriptions.Clear();
            dataView.SortDescriptions.Add(new SortDescription(c.SortMemberPath, ListSortDirection.Descending));
            dataView.Refresh();

но это не работает для меня.

1 Ответ

0 голосов
/ 28 августа 2018

Вы можете определить обработчик события как (неанонимный) метод:

private void grid_Sorting(object sender, DataGridSortingEventArgs args)
{
    //same code as before...
}

... и просто вызовите его после того, как вы установили свойство ItemsSource:

grid_Sorting(grid, new DataGridSortingEventArgs(grid.Columns[0])); //sort by the first column
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...