【发布时间】:2010-08-31 15:16:38
【问题描述】:
我正在使用绑定到 CollectionViewSource (players) 的 DataGrid,它本身绑定到 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# 代码 here,XAML 代码 here,整个测试项目 here - 除了 DataGrid,我还为玩家添加了一个简单的 ListBox,以确保它不是 DataGrid 问题)
问题是播放器在第一次显示时已排序,但一旦我从 ListBox 中选择另一个级别,它们就不再排序了。此外,在第一次显示玩家时修改名称会根据更改对它们进行排序,但在更改级别后就不会再更改了。
所以看起来更改 CollectionViewSource 的源以某种方式破坏了排序功能,但我不知道为什么,也不知道如何修复它。有谁知道我做错了什么?
(我使用过滤器进行了测试,但该过滤器一直按预期工作)
框架是 .NET 4。
【问题讨论】:
-
我以前也经历过同样的事情——不是每次都创建一个新对象,你能删除并重新插入它的内容吗?
-
除了额外的工作,这会通过创建/释放对象不必要地分割托管堆,如果可以的话,我宁愿避免它。
标签: wpf binding collectionviewsource