Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf sorting combobox item in alphabetical order

Tags:

c#

wpf

xaml

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:

<ComboBox Name="ModuleNames" >
                    <ComboBox.SelectedItem>
                        <Binding Path="ModuleDetails" NotifyOnValidationError="True">
                            <Binding.ValidationRules>
                                <validators:IsMandatoryValidation FieldName="Module Names"/>
                            </Binding.ValidationRules>
                        </Binding>
                    </ComboBox.SelectedItem>
                </ComboBox>
like image 898
sk123 Avatar asked Oct 25 '16 20:10

sk123


1 Answers

You should use a CollectionViewSource.

XAML:

You'll need to import the System.ComponentModel namespace as 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}}" />
like image 163
myermian Avatar answered Nov 15 '22 21:11

myermian