我正在使用一个绑定到CollectionViewSource(players)的DataGrid,CollectionViewSource(players)本身绑定到ListBox(levels)当前选择的项,每个项包含一个要在DataGrid中排序/显示的集合:
<ListBox Name="lstLevel"
DisplayMemberPath="Name"
IsSynchronizedWithCurrentItem="True" />
...
<!-- DataGrid source, as a CollectionViewSource to allow for sorting and/or filtering -->
<CollectionViewSource x:Key="Players"
Source="{Binding ElementName=lstLevel,
Path=SelectedItem.Players}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Name" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
...
<DataGrid Name="lstPlayers" AutoGenerateColumns="False"
CanUserSortColumns="False"
ItemsSource="{Binding Source={StaticResource Players}}">
<DataGrid.Columns>
<DataGridTextColumn Header="Name"
Binding="{Binding Path=Name, Mode=TwoWay}"
Width="*" />
<DataGridTextColumn Header="Age"
Binding="{Binding Path=Age, Mode=TwoWay}"
Width="80">
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
(完整的 C# 代码在这里,XAML 代码在这里,整个测试项目在这里 - 除了 DataGrid,我还添加了一个简单的 ListBox 来显示玩家信息,以确保问题不是出在 DataGrid 上)
问题是当玩家数据首次展现时它们已经排序,但是只要我从 ListBox 中选择另一个关卡,它们就不再排列。此外,在首次展示玩家并修改名称后,它们将根据更改排序,但是一旦更改了关卡,就不再工作。
所以看起来更改 CollectionViewSource 的来源会破坏排序功能,但我不知道为什么,也不知道如何解决。有人知道我做错了什么吗?
(我进行了筛选测试,但那个测试一直按预期工作)
框架是 .NET 4。