wpf按字母顺序排序组合框项目

时间:2016-10-25 20:03:39

标签: c#

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

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);
            }   
        }

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

1 个答案:

答案 0 :(得分:4)

您应该使用CollectionViewSource

<强> XAML:

<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}}" />

注意:您需要将System.ComponentModel命名空间导入为 scm