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

Wal*_*oni 24 .net c# wpf xaml 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));
Run Code Online (Sandbox Code Playgroud)

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

非常感谢,

最好的祝福,

Nixeus

Ada*_*abo 40

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

以下是基于不完整脚本的正确解决方案: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();
}
Run Code Online (Sandbox Code Playgroud)

如果您的代码,它可以像这样使用:

SortDataGrid(myDataGridEvenements, 0, ListSortDirection.Ascending);
Run Code Online (Sandbox Code Playgroud)

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

SortDataGrid(myDataGridEvenements);
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 6

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

(yourDataGrid.ItemsSource as DataView).Sort = "NAME_OF_COLUMN";
Run Code Online (Sandbox Code Playgroud)


Max*_*xim 6

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] });
}
Run Code Online (Sandbox Code Playgroud)


Stu*_*ioX 5

快速简单的方法:

dgv.Items.SortDescriptions.Clear();
dgv.Items.SortDescriptions.Add(new SortDescription("ID", ListSortDirection.Descending));
dgv.Items.Refresh();
Run Code Online (Sandbox Code Playgroud)