如何在更改DataGrid
后的ItemsSource
中保留列的排序?
以下代码保留了排序,但它没有将DataGrid
的列标题设置为“已排序”状态(因此没有“排序”图标和那些东西):
SortDescriptionCollection sortDescriptions = new SortDescriptionCollection();
foreach (SortDescription sd in OccupationsDataGrid.Items.SortDescriptions)
{
sortDescriptions.Add(sd);
}
OccupationsDataGrid.ItemsSource = q;
foreach (SortDescription sd in sortDescriptions)
{
OccupationsDataGrid.Items.SortDescriptions.Add(sd);
}
答案 0 :(得分:0)
使用Telerik的JustDecompile并查看DataGrid。
在DataGrid的静态构造函数中,我们有这一行:
ItemsControl.ItemsSourceProperty.OverrideMetadata(type, new FrameworkPropertyMetadata(null, new CoerceValueCallback(DataGrid.OnCoerceItemsSourceProperty)));
因此,当ItemsSource更改时,将调用DataGrid.OnCoerceItemsSourceProperty。它被定义为:
private static object OnCoerceItemsSourceProperty(DependencyObject d, object baseValue)
{
DataGrid dataGrid = (DataGrid)d;
if (baseValue != dataGrid._cachedItemsSource && dataGrid._cachedItemsSource != null)
{
dataGrid.ClearSortDescriptionsOnItemsSourceChange();
}
return baseValue;
}
最终调用ClearSortDescriptionsOnItemsSourceChange。这是:
private void ClearSortDescriptionsOnItemsSourceChange()
{
base.Items.SortDescriptions.Clear();
this._sortingStarted = false;
List<int> groupingSortDescriptionIndices = this.GroupingSortDescriptionIndices;
if (groupingSortDescriptionIndices != null)
{
groupingSortDescriptionIndices.Clear();
}
foreach (DataGridColumn column in this.Columns)
{
column.SortDirection = null;
}
}
看来列的SortDirection正在被清除,并且必须控制排序箭头的外观。所以...当我们添加排序描述时,我们应该把它放回去。更改重新添加SortDescriptions的循环:
foreach (SortDescription sd in sortDescriptions)
{
OccupationsDataGrid.Items.SortDescriptions.Add(sd);
foreach (var col in OccupationsDataGrid.Columns.Where(aa => aa.SortMemberPath == sd.PropertyName))
{
col.SortDirection = sd.Direction;
}
}