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

C# 以编程方式对wpf数据网格进行排序,c#,.net,wpf,xaml,datagrid,C#,.net,Wpf,Xaml,Datagrid,是否有一种方法可以对WPF DataGrid程序进行排序(例如,如果单击第一列) 有没有办法模拟这种点击?还是最好的方法 这是我的代码: Collection_Evenements = new ObservableCollection<Evenement>(); Collection_Evenements = myEvenement.GetEvenementsForCliCode(App.obj_myClient.m_strCode); Collection_Evenements.

是否有一种方法可以对WPF DataGrid程序进行排序(例如,如果单击第一列)

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

这是我的代码:

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));
Collection\u events=新的ObservableCollection();
Collection\u events=myEvenement.GetEvenementsForCliCode(App.obj\u myClient.m\u strCode);
Collection\u events.CollectionChanged+=Collection\u events\u CollectionChanged;
MyDataGridEvenments.ItemsSource=集合\u Evenments;
System.Data.DataView dv=(System.Data.DataView)MyDataGridEvents.ItemsSource;
dv.Sort=“strEvtType”;
myDataGridEvenments.Focus();
MyDataGridEvents.SelectedIndex=0;
MoveFocus(新的遍历请求(FocusNavigationDirection.Next));
我不知道为什么,但是行“dv.Sort=”strEvtType“;”引起了一件奇怪的事情,我的窗口出现了,程序不会继续执行下一行,尽管我没有看到排序

非常感谢

致以最良好的祝愿


Nixeus

获取ItemsSource的DataView并使用其Sort属性指定排序依据的列:

(yourDataGrid.ItemsSource as DataView).Sort = "NAME_OF_COLUMN";
您可以使用在datagrid中对项目进行筛选、排序和分组

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


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

这里有一个基于不完整脚本的正确解决方案:

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

SortDataGrid(myDataGridEvenements, 0, ListSortDirection.Ascending);
或者通过使用默认参数值,只需:

SortDataGrid(myDataGridEvenements);
我的方法是为我工作。 试试这个代码。对不起,俄罗斯人

// Если таблица пустая, то привязываем ее к журналу 
            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();
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] });
}
快速简便的方法:

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

您不能对DataGrid视图进行排序吗?然后刷新布局?你有一个例子吗?你是怎么做到的?谢谢如果您不绑定到对象集合而是绑定到数据表,那么您必须使用IBindingListView.Filter()您好,谢谢您的回答。列的名称是什么,“header”属性是什么?我找不到name属性:(@WalterFabioSimoni不,这是您绑定到数据网格的源列的名称。好的,明白了!但是当程序进入.Sort行时,我的程序窗口显示出来,仅此而已!它是strange@WalterFabioSimoni您的Evenement类型的结构是什么?我想您应该传递Evenement的属性名,你想按它排序。很棒的方法,易于使用和修改。谢谢。工作很有魅力,ty:D
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] });
}
dgv.Items.SortDescriptions.Clear();
dgv.Items.SortDescriptions.Add(new SortDescription("ID", ListSortDirection.Descending));
dgv.Items.Refresh();