wpf 对组合框中的项目进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23908278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting the items in a combobox
提问by pankaj
I have a combobox binded to an observable collection. I am using CollectionViewSource to sort the items in the combobox alphabetically.
我有一个绑定到可观察集合的组合框。我正在使用 CollectionViewSource 按字母顺序对组合框中的项目进行排序。
<CollectionViewSource x:Key="EmployeeViewSource" Source="{Binding LstEmployeeDetails}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="EmployeeName" Direction="Ascending"/>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
And then I bind it to my combobox like this:
然后我像这样将它绑定到我的组合框:
<ComboBox x:Name="CmbboxEmployeeName" ItemsSource="{Binding Source={StaticResource EmployeeViewSource}}"/>
The problem is I have two items in the collection that I don't want to sort. They are
问题是我不想对集合中有两个项目进行排序。他们是
--Select-- and "Add New". I want that these two items should always be displayed on top and then the rest of the items should be sorted alphabetically. Also, when I add a new item to the list, it should get sorted automatically.
--选择--和“添加新”。我希望这两个项目应始终显示在顶部,然后其余项目应按字母顺序排序。此外,当我向列表中添加新项目时,它应该会自动排序。
回答by Max
You can bind your ComboBoxto an ObservableCollectionin your ViewModel and sort it in code:
您可以将您的绑定ComboBox到ObservableCollectionViewModel 中的an并在代码中对其进行排序:
C#:
C#:
public class ViewModel
{
public ObservableCollection<Employee> List { get; set; }
public ViewModel()
{
List = new ObservableCollection<Employee>();
List.Add("Select");
List.Add("Add New");
foreach (var employee in LstEmployeeDetails.OrderBy(e => e.EmployeeName))
{
List.Add(employee);
}
}
}
XAML:
XAML:
<ComboBox x:Name="CmbboxEmployeeName" ItemsSource="{Binding List}"/>

