对ObservableCollection进行排序

时间:2011-04-27 12:04:16

标签: c# .net wpf sorting 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”) 通过用户从组合框中进行适当选择[它将... ...排序FirstName ...。排序由MobileNumber等...] ..

需要取回已排序的可观察集合...... 意味着不应该是“var”的形式 ObservableCollection<Employee>

因此,我可以将其分配回“ItemsSource”的{​​{1}}属性...

感谢......

4 个答案:

答案 0 :(得分: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 :(得分:3)

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

http://softcollections.codeplex.com/

答案 2 :(得分:2)

我实现了一个ObservableCollectionView,它支持使用lambda(如LINQ但是直播)和项目跟踪进行排序和过滤:

https://mytoolkit.codeplex.com/wikipage?title=ObservableCollectionView

答案 3 :(得分:1)

你不需要自己排序,但可以让WPF为你做。例如,请参阅SortDescription

相关问题