以编程方式对 wpf 数据网格进行排序 [英] Sort a wpf datagrid programmatically

查看:34
本文介绍了以编程方式对 wpf 数据网格进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to sort a WPF DataGrid programmatically (for example, like if I clicked on my first column)?

有没有办法模拟这次点击?

Is there a way to simulate this click?

这是我的代码:

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"; 行导致了一个奇怪的事情,我的窗口出现了,程序没有继续执行下一行,不过,我看不到那种!

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

推荐答案

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

voo's solution was not working for me, ItemsSource was 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 DataGrid header was not reflecting to the sort.

这里有一个基于不完整脚本的正确解决方案:http://dotnetgui.blogspot.co.uk/2011/02/how-to-properly-sort-on-wpf-datagrid.html

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

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

这篇关于以编程方式对 wpf 数据网格进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆