C# 以编程方式对 wpf 数据网格进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16956251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:13:48  来源:igfitidea点击:

Sort a wpf datagrid programmatically

c#.netwpfxamldatagrid

提问by Walter Fabio Simoni

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

有没有办法以编程方式对 WPF DataGrid 进行排序(例如,如果我点击了我的第一列)。

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

有没有办法模拟这次点击?还是最好的方法?

Here is my code :

这是我的代码:

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));

I don't know why, but the line "dv.Sort = "strEvtType";" cause a strange thing, my Window Show up and the programme don't continue to execute the next lines, nevertheless i don't see the sort !

我不知道为什么,但是 "dv.Sort = "strEvtType";" 导致奇怪的事情,我的窗口出现并且程序不会继续执行下一行,但是我没有看到排序!

Thanks a lot,

非常感谢,

Best regards,

此致,

Nixeus

尼克斯

回答by Alex

Get your ItemsSource's DataView and use its Sort property to specify the column you are sorting by:

获取您的 ItemsSource 的 DataView 并使用其 Sort 属性来指定您正在排序的列:

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

回答by blindmeis

you can use ICollectionViewto filter, sort and group your items in a datagrid.

您可以使用ICollectionView对数据网格中的项目进行过滤、排序和分组。

EDIT: add Sort, did not read the question carefully :)

编辑:添加排序,没有仔细阅读问题:)

 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;


   }

回答by Adam Szabo

voo's solution was not working for me, ItemsSourcewas null, most likely because it was not directly set, but bound. All other solutions I found here at StackOverflow were dealing with sorting the Model only, but the DataGridheader was not reflecting to the sort.

voo 的解决方案对我不起作用,ItemsSource为空,很可能是因为它不是直接设置的,而是绑定的。我在 StackOverflow 上找到的所有其他解决方案都只处理对模型进行排序,但DataGrid标题并未反映排序。

Here's a proper solution based on the incomplete script here: http://dotnetgui.blogspot.co.uk/2011/02/how-to-properly-sort-on-wpf-datagrid.html

这是基于此处不完整脚本的正确解决方案: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();
}

In case of your code, it can be used like this:

对于您的代码,它可以像这样使用:

SortDataGrid(myDataGridEvenements, 0, ListSortDirection.Ascending);

Or by using the default parameter values, simply:

或者通过使用默认参数值,只需:

SortDataGrid(myDataGridEvenements);

回答by vajarkov

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();

回答by Maxim

PerformSortmethod of the DataGrid is what actually executed on a column's header click. However this method is internal. So if you really want to simulate the clickyou need to use reflection:

DataGrid 的PerformSort方法是在列的标题单击时实际执行的方法。然而,这种方法是内部的。所以如果你真的想模拟点击你需要使用反射:

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] });
}

回答by StudioX

Fast & Easy way:

快速简便的方法:

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