WPF按字母顺序排序组合框项

本文关键字:组合 排序 顺序 WPF | 更新日期: 2023-09-27 18:14:58

我有一个组合框。这个组合框内的项目来自数据库,我正试图按字母顺序排序,但无法这样做。有人能帮忙弄清楚这是如何实现的吗?

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:

<ComboBox Name="ModuleNames" >
                    <ComboBox.SelectedItem>
                        <Binding Path="ModuleDetails" NotifyOnValidationError="True">
                            <Binding.ValidationRules>
                                <validators:IsMandatoryValidation FieldName="Module Names"/>
                            </Binding.ValidationRules>
                        </Binding>
                    </ComboBox.SelectedItem>
                </ComboBox>

WPF按字母顺序排序组合框项

您应该使用CollectionViewSource

XAML:

您需要导入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}}" />