【发布时间】:2019-01-24 04:56:04
【问题描述】:
我有以下简单的代码可以重现这个问题:
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时消失,但排序仍然正确。
这是 WPF DataGrid 控件中的错误还是我在这里遗漏了什么?
【问题讨论】:
标签: c# wpf wpfdatagrid collectionviewsource