我有以下简单的代码可以重现此问题:
XAML:
<DataGrid ItemsSource="{Binding Source.View}"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name"
Binding="{Binding Name}"
SortMemberPath="Name"
SortDirection="Ascending"/>
</DataGrid.Columns>
</DataGrid>
查看模型:
private readonly ObservableCollection<Data> _collection1 = new ObservableCollection<Data> {new Data("item 1"), new Data("item 2")};
private readonly ObservableCollection<Data> _collection2 = new ObservableCollection<Data> {new Data("person 1"), new Data("person 2")};
public MainViewModel()
{
Source.Source = _collection1;
// Set up a timer that runs 5 seconds.
Observable.Timer(TimeSpan.FromSeconds(5)).ObserveOn(AsyncOperationManager.SynchronizationContext).Subscribe(_ =>
{
// Get existing sort descriptions.
var existingSortDescription = Source.View.SortDescriptions.ToList();
// Change source.
Source.Source = _collection2;
// This has to be done in order to maintain the sort order.
existingSortDescription.ForEach(Source.SortDescriptions.Add);
});
}
public CollectionViewSource Source { get; } = new CollectionViewSource();
private class Data
{
public Data(string name)
{
Name = name;
}
public string Name { get; }
}
因此,上面的代码所做的是,当应用程序启动时,将其_collection1
用作数据网格的项目源。
5秒后,将数据网格的项目源更改为_collection2
。
如果运行上面的代码,则将源更改为时,“名称”列标题中的排序方向箭头将消失_collection2
,但是排序仍然正确。
这是WPFDataGrid
控件中的错误还是我在这里丢失了一些东西?
在SortDescriptions
您添加到View
的CollectionViewSource
视图模型不影响箭头,你在看到DataGrid
的视图控件。
您可以通过设置特定列的SortDirection
属性以编程方式显示该列的箭头。因此,您可以做的是创建一个自定义控件DataGrid
来为您处理此操作(内置控件不会像您已经发现的那样),例如:
public class CustomDataGrid : DataGrid
{
protected override void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
{
base.OnItemsSourceChanged(oldValue, newValue);
INotifyCollectionChanged oldView = oldValue as INotifyCollectionChanged;
if (oldView != null)
oldView.CollectionChanged -= View_CollectionChanged;
INotifyCollectionChanged newView = newValue as INotifyCollectionChanged;
if (newView != null)
newView.CollectionChanged += View_CollectionChanged;
}
private void View_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
ICollectionView view = sender as ICollectionView;
if (view != null)
{
SortDescription sd = view.SortDescriptions.LastOrDefault();
if (sd != null)
{
DataGridColumn column = Columns.FirstOrDefault(x => x.SortMemberPath == sd.PropertyName);
if (column != null)
{
column.SortDirection = sd.Direction;
}
}
}
}
}
然后,您只需用XAML中的元素替换您的<DataGrid />
元素<local:CustomDataGrid />
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句