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