Подтвердить что ты не робот

Сортировка wpf datagrid программно

Есть ли способ сортировки WPF DataGrid programmaticaly (например, как если бы я нажал на мой первый столбец).

Есть ли способ имитировать этот клик? Или лучший способ?

Вот мой код:

Collection_Evenements = new ObservableCollection<Evenement>();

Collection_Evenements = myEvenement.GetEvenementsForCliCode(App.obj_myClient.m_strCode);
Collection_Evenements.CollectionChanged += Collection_Evenements_CollectionChanged;
myDataGridEvenements.ItemsSource = Collection_Evenements;

System.Data.DataView dv = (System.Data.DataView)myDataGridEvenements.ItemsSource;
dv.Sort = "strEvtType";

myDataGridEvenements.Focus();
myDataGridEvenements.SelectedIndex = 0;
myDataGridEvenements.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

Я не знаю почему, но строка "dv.Sort =" strEvtType ";" вызывают странную вещь, мой Window Show и программа не продолжают выполнять следующие строки, тем не менее я не вижу сортировку!

Большое спасибо,

С уважением,

Nixeus

4b9b3361

Ответ 1

Решение voo для меня не работало, ItemsSource было null, скорее всего, потому что оно не было напрямую задано, но связано. Все другие решения, которые я нашел здесь в StackOverflow, касались сортировки только модели, но заголовок DataGrid не отражался на сортировке.

Здесь правильное решение, основанное на неполном script здесь: http://dotnetgui.blogspot.co.uk/2011/02/how-to-properly-sort-on-wpf-datagrid.html

public static void SortDataGrid(DataGrid dataGrid, int columnIndex = 0, ListSortDirection sortDirection = ListSortDirection.Ascending)
{
    var column = dataGrid.Columns[columnIndex];

    // Clear current sort descriptions
    dataGrid.Items.SortDescriptions.Clear();

    // Add the new sort description
    dataGrid.Items.SortDescriptions.Add(new SortDescription(column.SortMemberPath, sortDirection));

    // Apply sort
    foreach (var col in dataGrid.Columns)
    {
        col.SortDirection = null;
    }
    column.SortDirection = sortDirection;

    // Refresh items to display sort
    dataGrid.Items.Refresh();
}

В случае вашего кода его можно использовать следующим образом:

SortDataGrid(myDataGridEvenements, 0, ListSortDirection.Ascending);

Или, используя значения параметров по умолчанию, просто:

SortDataGrid(myDataGridEvenements);

Ответ 2

Получите DataSource DataView и используйте его свойство Сортировка, чтобы указать сортировку столбца:

(yourDataGrid.ItemsSource as DataView).Sort = "NAME_OF_COLUMN";

Ответ 3

Метод PerformSort DataGrid - это то, что фактически выполняется при щелчке заголовка столбца. Однако этот метод является внутренним. Поэтому, если вы действительно хотите, чтобы имитировал щелчок, вам нужно использовать отражение:

public static void SortColumn(DataGrid dataGrid, int columnIndex)
{
    var performSortMethod = typeof(DataGrid)
                            .GetMethod("PerformSort",
                                       BindingFlags.Instance | BindingFlags.NonPublic);

    performSortMethod?.Invoke(dataGrid, new[] { dataGrid.Columns[columnIndex] });
}

Ответ 4

Мой метод работает для меня. Просто попробуйте этот код. Извините за русский

// Если таблица пустая, то привязываем ее к журналу 
            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();

Ответ 5

вы можете использовать ICollectionView для фильтрации, сортировки и группировки ваших элементов в datagrid.

ИЗМЕНИТЬ: добавьте Сортировку, не прочитал вопрос внимательно:)

 var view = CollectionViewSource.GetDefaultView(this.MyData);
 view.Filter = ViewFilter;
 view.SortDescriptions.Add(new SortDescription("MyPropertyToSort", ListSortDirection.Descending));


    private bool ViewFilter(object obj)
    {
        var item = obj as MyObject;

        if (item == null)
            return false;

        //your filter logik goes here

        if(item.MyStringProp.StartsWith("Test"))
            return false;

        return true;


   }

Ответ 6

Fast & Простой способ:

dgv.Items.SortDescriptions.Clear();
dgv.Items.SortDescriptions.Add(new SortDescription("ID", ListSortDirection.Descending));
dgv.Items.Refresh();