2011-04-27 93 views
14

假设我有Employee类的ObservableCollection排序的ObservableCollection

public ObservableCollection<Employee> employeeCollection = new ObservableCollection<Employee>(); 

public class Employee 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public double MobileNumber { get; set; } 
    public string City { get; set; } 
    public int Age { get; set; } 

    public Employee() {} 
} 

我现在想通过组合框的用户进行排序ObservableCollection(“employeeCollection”) 适当选择[这将是...的.sort通过名字... .Sort By MobileNumber etc ...]

并且它需要取回已排序的可观察集合...。 意味着它不应该在“VAR”的形式,它应该是 ObservableCollection<Employee>

所以我可以分配回它的“ItemsControl”“ItemsSource”财产......

感谢......

+2

你为什么要排序的集合?您还可以对数据绑定执行排序。 – PVitt 2011-04-27 12:06:19

+0

[在我的应用程序中,“Item controle”显示每个员工都在可观察的集合中,现在我想对可观察的集合进行排序,因此我的应用程序的UI将根据可观察的集合进行排序......谢谢] – Pritesh 2011-04-27 12:14:06

+0

当您接受答案时... – PVitt 2011-12-08 08:44:35

回答

27

您可以按该集合的意见,而不是排序集合本身:

// xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase" 
<myView.Resources> 
    <CollectionViewSource x:Key="ItemListViewSource" Source="{Binding Itemlist}"> 
     <CollectionViewSource.SortDescriptions> 
      <scm:SortDescription PropertyName="SortingProperty" /> 
     </CollectionViewSource.SortDescriptions> 
    </CollectionViewSource> 
</myView.Resources> 

然后你可以使用CollectionViewSource为的ItemSource:

ItemsSource="{Binding Source={StaticResource ItemListViewSource}}" 
+1

请注意'PropertyName'不能使用绑定。它直接导致以下运行时错误:'A'Binding'不能在'SortDescription'类型的'PropertyName'属性上设置。 '绑定'只能在DependencyObject的DependencyProperty上设置。' – 2014-05-25 14:42:44

+0

@OndrejJanacek这是新的行为吗?我可以发誓我以这种方式使用它。但是我再也无法访问代码来检查它了。 – PVitt 2014-05-26 07:25:53

+0

@好吧,你以这种方式使用它并不是很有效。该属性毕竟被称为'PropertyName',它表明它可以接受一个属性的字符串名称,而不是直接绑定它。但是我对WPF很陌生,我只是偶然发现了这一点,因为我正在寻找解决方案并且实现了它,所以也许可能它以前是以另一种方式工作的。 – 2014-05-26 09:45:06

1

你并不需要自己进行排序,但可以让WPF为你做它。例如,见SortDescription

3

我认为PVitt可能有最好的解决方案...但是,我确实发现这个 SortedObservableCollection类可能可以帮助吗?

http://softcollections.codeplex.com/

+1

排序的可观察集合的替代实现:[ObservableSortedList ](https://bitbucket.org/rstarkov/wpfcrutches/src/tip/ObservableSortedList.cs)。 – 2012-04-13 14:29:21

相关问题