对ObservableCollection进行排序

Pri*_*esh 14 .net c# sorting wpf 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() {}
}
Run Code Online (Sandbox Code Playgroud)

现在我试图ObservableCollection通过用户从组合框中进行适当的选择来对("employeeCollection")进行排序[它将... ...排序FirstName ... .Sort By MobileNumber等...]

并且需要返回已排序的可观察集合.... 意味着它不应该是"var"的形式 ObservableCollection<Employee>

所以我可以将它归还给...的“ItemsSource”财产“ItemsControl”

谢谢……

PVi*_*itt 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>
Run Code Online (Sandbox Code Playgroud)

然后您可以将CollectionViewSource用作ItemSource:

ItemsSource="{Binding Source={StaticResource ItemListViewSource}}"
Run Code Online (Sandbox Code Playgroud)