Sort a wpf datagrid programmatically

前端 未结 6 2408
攒了一身酷
攒了一身酷 2020-11-29 08:22

Is there a way to sort a WPF DataGrid programmaticaly ( for example, like if i clicked on my first column).

Is there a way to simuate this click ? Or a best way ?

6条回答
  •  情歌与酒
    2020-11-29 08:43

    My method is work for me. Just try this code. Sorry for Russian

    // Если таблица пустая, то привязываем ее к журналу 
                if(dgEvents.ItemsSource == null)
                    dgEvents.ItemsSource = events.Entries;
                // Обновляем записи
                CollectionViewSource.GetDefaultView(dgEvents.ItemsSource).Refresh();
                // Очищаем описание сортировки
                dgEvents.Items.SortDescriptions.Clear();
                // Созадем описание сортировки
                dgEvents.Items.SortDescriptions.Add(new SortDescription(dgEvents.Columns[0].SortMemberPath, ListSortDirection.Descending));
    
                // Очищаем сортировку всех столбцов
                foreach (var col in dgEvents.Columns)
                {
                    col.SortDirection = null;
                }
                // Задаем сортировку времени по убыванию (последняя запись вверху)
                dgEvents.Columns[0].SortDirection = ListSortDirection.Descending;
                // Обновляем записи
                dgEvents.Items.Refresh();
    

提交回复
热议问题