wpf 按字母顺序排序组合框项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40248742/
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
wpf sorting combobox item in alphabetical order
提问by sk123
I have got combobox. The items within this combobox is coming from database and I am trying to sort it in alphabetical order but unable to do so. Can someone please help figuring out how this can be achieved?
我有组合框。此组合框中的项目来自数据库,我试图按字母顺序对其进行排序,但无法这样做。有人可以帮助弄清楚如何实现这一目标吗?
private ObservableCollection<StudentModules> modules;
public StudentModule()
{
InitializeComponent();
DataContext = this;
Modules = new ObservableCollection<StudentModules>();
ModuleNames.ItemsSource = modules;
IDataAccess<ModulesFinder, StudentModules> moduleRetriever = ((IDataManager)Application.Current.Properties["Database”]).GetDataAccessor<ModuleFinder, StudentModules>();
foreach (StudentModules module in retrieve.AllItems())
{
Modules.Add(module);
}
}
XAML:
XAML:
<ComboBox Name="ModuleNames" >
<ComboBox.SelectedItem>
<Binding Path="ModuleDetails" NotifyOnValidationError="True">
<Binding.ValidationRules>
<validators:IsMandatoryValidation FieldName="Module Names"/>
</Binding.ValidationRules>
</Binding>
</ComboBox.SelectedItem>
</ComboBox>
回答by m-y
You should use a CollectionViewSource.
你应该使用一个CollectionViewSource.
XAML:
XAML:
You'll need to import the System.ComponentModelnamespace as scm.
您需要将System.ComponentModel命名空间导入为scm。
<UserControl.Resources>
<CollectionViewSource x:Key="ModulesViewSource" Source="{Binding Path=Modules}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Name" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</UserControl.Resources>
...
<ComboBox ItemsSource="{Binding Source={StaticResource ModulesViewSource}}" />

