WPF DataGrid MultiColumn сортировка без клавиши Shift - PullRequest
3 голосов
/ 05 мая 2011

WPF DataGrid имеет поведение по умолчанию, разрешающее многоколоночные сортировки, когда пользователь нажимает клавишу Shift на заголовках нескольких столбцов.Есть ли способ изменить это поведение, чтобы клавиша Shift не требовалась?Я уже обработал событие сортировки в сетке данных, так что каждый столбец будет циклически переключаться между тремя состояниями сортировки (По возрастанию, По убыванию и Без сортировки), и все это работает должным образом, пока нажата клавиша Shift, но я бы хотелхотелось бы сделать так, чтобы DataGrid не сбрасывал сортировку по всем другим столбцам, если пользователь щелкает заголовок столбца, чтобы добавить сортировку без нажатия клавиши shift.

Ответы [ 2 ]

1 голос
/ 10 мая 2011

Я нашел решение, которое кажется немного взломанным, но оно работает. Эта статья подтолкнула меня к правильному направлению: http://blogs.msdn.com/b/vinsibal/archive/2008/08/29/wpf-datagrid-tri-state-sorting-sample.aspx?PageIndex=2. Это привело меня к пониманию, что SortDirection каждого столбца на самом деле никак не связан с SortDescription ItemsSource. Поэтому я подписался на событие Sorting Datagrid и сбросил SortDirection для каждого столбца, на который есть ссылка в коллекции ItemsSource SortDescription. Очевидно, что нажатие клавиши shift не очищает направление сортировки каждого столбца, но не сбрасывает SortDescription.

0 голосов
/ 09 декабря 2016

Я имел дело с той же проблемой, но никто не показал код, который может решить эту проблему.Вопрос старый, но я надеюсь, что решение будет полезно для искателей.

(DataGrid.Items.SortDescriptions as INotifyCollectionChanged).CollectionChanged += OnGridCollectionChanged;

 private void OnGridCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
        {
            var sortingCollection = (SortDescriptionCollection)sender;
            foreach (var sortDesc in sortingCollection)
            {
                foreach (var column in SignaturesInImagingGrid.Columns)
                {
                    if (column.SortMemberPath.Equals(sortDesc.PropertyName))
                    {
                        column.SortDirection = sortDesc.Direction;
                    }
                }
            }
        }

<DataGrid Sorting="GridMultiColumnSortingEvent">

public static void GridMultiColumnSortingEvent(object sender, DataGridSortingEventArgs e)
        {
            var dgSender = (DataGrid)sender;
            var cView = CollectionViewSource.GetDefaultView(dgSender.ItemsSource);

            ListSortDirection direction = ListSortDirection.Ascending;
            if (ContainsSortColumn((DataGrid)sender, e.Column.SortMemberPath))
            {
                if (e.Column.SortDirection == null)
                {
                    direction = ListSortDirection.Ascending;
                    ChangeSortColumn((DataGrid)sender, e.Column, direction);
                }
                else if (DirectionForColumn(cView, e.Column) == ListSortDirection.Ascending)
                {
                    direction = ListSortDirection.Descending;
                    ChangeSortColumn((DataGrid)sender, e.Column, direction);
                }
                else if (DirectionForColumn(cView, e.Column) == ListSortDirection.Descending)
                {
                    e.Column.SortDirection = null;
                    cView.SortDescriptions.Remove(cView.SortDescriptions.Where(item => item.PropertyName.Equals(e.Column.SortMemberPath)).FirstOrDefault());
                    cView.Refresh();
                }
            }
            else
            {
                AddSortColumn((DataGrid)sender, e.Column.SortMemberPath, direction);
                cView.Refresh();
            }
            e.Handled = true;
        }

        private static ListSortDirection DirectionForColumn(ICollectionView cView, DataGridColumn column) =>
            cView.SortDescriptions.Where(item => item.PropertyName.Equals(column.SortMemberPath))
                 .FirstOrDefault()
                 .Direction;

        private static void AddSortColumn(DataGrid sender, string sortColumn, ListSortDirection direction)
        {
            var cView = CollectionViewSource.GetDefaultView(sender.ItemsSource);
            cView.SortDescriptions.Add(new SortDescription(sortColumn, direction));
            foreach (var col in sender.Columns.Where(x => x.SortMemberPath == sortColumn))
            {
                col.SortDirection = direction;
            }
        }

        private static void ChangeSortColumn(DataGrid sender, DataGridColumn column, ListSortDirection direction)
        {
            var cView = CollectionViewSource.GetDefaultView(sender.ItemsSource);
            string sortColumn = column.SortMemberPath;

            foreach (var sortDesc in cView.SortDescriptions.ToList())
            {
                if (sortDesc.PropertyName.Equals(sortColumn))
                {
                    cView.SortDescriptions.Remove(sortDesc);
                    break;
                }
            }

            AddSortColumn(sender, sortColumn, direction);
        }

        private static bool ContainsSortColumn(DataGrid sender, string sortColumn)
        {
            var cView = CollectionViewSource.GetDefaultView(sender.ItemsSource);
            foreach (var sortDesc in cView.SortDescriptions.ToList())
            {
                if (sortDesc.PropertyName.Equals(sortColumn))
                    return true;
            }
            return false;
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...