排序WPF数据网格编程 [英] Sort a wpf datagrid programmatically
问题描述
有没有一种方法,以一个WPF DataGrid的排序programmaticaly(例如,就像如果我点击我的第一列)。
Is there a way to sort a WPF DataGrid programmaticaly ( for example, like if i clicked on my first column).
有没有办法来simuate这个点击?还是最好的方法是什么?
Is there a way to simuate this click ? Or a best way ?
这是我的code:
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";" cause a strange thing, my Window Show up and the programme don't continue to execute the next lines, nevertheless i don't see the sort !
感谢了很多,
最好的问候,
Nixeus
推荐答案
VOO的解决方案并没有为我工作,的ItemsSource
为空,最有可能的,因为它不直接设置,但约束。
所有其他解决方案,我发现这里的计算器正在处理只排序模式,但的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.
下面是一个基于位置的不完整的脚本一个妥善的解决办法:<一href="http://dotnetgui.blogspot.co.uk/2011/02/how-to-properly-sort-on-wpf-datagrid.html">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();
}
如果你的code,它可以是这样的:
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屋!