2014-01-27 43 views
0

我使用EnumDescription值填充ListBox。这些以Enum的索引顺序显示,但我希望它们按说明进行排序。所以我给ListBox加了一个SortDescription,但它不起作用。如何对绑定的ObjectDataProvider集合进行排序?

ObjectDataProvider odp = new ObjectDataProvider() 
{ 
    IsInitialLoadEnabled = false, 
    MethodName = "GetValues", 
    ObjectType = typeof(Enum), 
}; 
odp.MethodParameters.Add(this.EnumType); 
odp.Refresh(); 
Binding b = new Binding() { Source = odp }; 
listBox.SetBinding(ListBox.ItemsSourceProperty, b); 
listBox.Items.SortDescriptions.Add(new SortDescription()); 

我也试着属性名称添加到SortDescription,但我不知道是哪一个(我试过“价值”和“说明”)。

ObjectDataProvider包装在CollectionViewSource中,并对该集合进行排序也无济于事。

有没有解决方案?

回答

1

什么的ObjectDataProvider的目的,如果你的绑定是代码?

var sortedValues = Enum.GetValues(typeof(MyEnum)) 
    .Cast<MyEnum>() 
    .OrderBy(v => v.ToString()) 
    .ToArray(); 

Binding b = new Binding() { Source = sortedValues }; 
+0

谢谢,它的工作原理。该代码曾在XAML中出现过一些原因。不记得为什么了。最后一个'ToArray()'不是必须的。 – gumo

相关问题