我有组合框。此组合框中的项目来自数据库,我正在尝试按字母顺序对其进行排序,但无法这样做。有人可以帮忙弄清楚如何实现这一目标吗?

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>

最佳答案

您应该使用 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}}" />

关于c# - wpf排序组合框项按字母顺序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40248742/

10-17 01:44