我在使用SortDescription时遇到了问题。我发现了一些关于这个问题的线索,比如如果你想按照一个没有实现IComparable的类型进行排序,就像用户定义的类一样,但这不是我的情况。使用WPF中的SortDescription问题 - int和string不是IComparable?
我有一个类,它有两个属性:字符串ID和int值。我们称之为物品! 我有一个观点:
<UserControl> <!-- ... -->
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button Click="Button_Click"
Content="Sort by ID"
Grid.Row="0"/>
<Button Click="Button_Click1"
Content="Sort by Value"
Grid.Row="1"/>
<DockPanel Grid.Row="2">
<ItemsControl x:Name="mItemsControl"
ItemsSource="{Binding Items}"><!-- The type of Items is ObservableCollection<Item> -->
<!-- ... -->
</ItemsControl>
</DockPanel>
</Grid>
</GroupBox>
事件处理是这样的:“失败的阵列中来比较两个元素”
private void Button_Click(object sender, RoutedEventArgs e)
{
mItemsControl.Items.SortDescriptions.Add(new SortDescription("ID", ListSortDirection.Ascending); //Exception here
}
private void Button_Click1(object sender, RoutedEventArgs e)
{
mItemsControl.Items.SortDescriptions.Add(new SortDescription("Value", ListSortDirection.Ascending); //...and here as well
}
我得到InvalidOperationException异常,因为它,这是因为两者都不元素实现IComparable。 也就是说,我无法理解,因为我可以比较整数以及字符串。
感谢您的任何想法!
我是个骗子。我的例子太不精确了。 mItemsControl.Items.SortDescriptions.Add(this.IDDescending);是我用过的,其中IDAscending的getter创建了一个新的SortDescription(“ID”,ListSortDirection.Descending),但正如我发现的那样,通过这种方式得到的值是某种默认的Sortdescription。它的方向是升序,而PropertyName是空的。 (我使用该解决方案能够添加和删除确切的sortdescriptions。) 我不知道为什么,但这个shuld是答案。 – ike 2010-12-03 15:40:38