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

标签 c# .net wpf xaml datagrid

有没有办法以编程方式对 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));

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

最佳答案

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

这里有一个基于不完整脚本的正确解决方案: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);

关于c# - 以编程方式对 wpf 数据网格进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16956251/

相关文章:

c# - 从 .NET 加载 WinRT 程序集

c# - 如何通过 ViewModel 控制 View VisualState

c# - 如何将 WPF UserControl 从一个窗口移动到另一个窗口?

c# - WPF 如何单击 DataGrid 中的行以取消选择项目

c# - 使用 Linq to Entities 获取唯一值

c# - EF 6 加上几个数据库上下文

c# - Plinq 给出了与 Linq 不同的结果——我做错了什么?

c# - 在 HPUX 上运行 C#

c# - 使用异步/等待模式在 C# 5 中编写高度可扩展的 TCP/IP 服务器?

c# - 如何最好地应用WPF MVVM?