I have a lot off combo boxes in my project. I need to sort there items alphabetically. I can't sort them individually in SQL query not through LINQ where data in loading . I want to put a hook in Combox ,whenever any combox get data in project it sort in automatically. How I can do that ? What and where changes should I made to generically sort all combobox.
CodePudding user response:
You can use CollectionViewSource
On XAML side: Here you need to set cm as namespace
xmlns:cm="clr-namespace:System.ComponentModel;assembly=System"
...
<UserControl.Resources>
<CollectionViewSource x:Key="MyViewSource" Source="{Binding Path=YourItemSource}">
<CollectionViewSource.SortDescriptions>
<cm:SortDescription PropertyName="Name" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</UserControl.Resources>
... Usage ..
<ComboBox ItemsSource="{Binding Source={StaticResource MyViewSource}}" />
CodePudding user response:
First, all values that are meaningful for the sort must be provided through the properties of the collection item.
If you need only one sort of sort for each collection, then use the CollectionViewSource.GetDefaultView (object) method and get a CollectionView for your collection.
Add sorting descriptors to the SortDescriptions property: the name of the property and the direction of sorting.
After that, any ItemsControl (including ComboBox) will present your collection in a sorted form.
If one collection needs several different sorts.
Then for each you will have to create a separate CollectionView.
To do this, create an instance of the CollectionViewSource - usually done in XAML resources.
You bind its Source property to your source collection.
Set sort descriptors.
If you need dynamic coding (that is, the values of the properties of elements can change after they are placed in the collection), then assign the IsLiveSortingRequested property to true.
After that, bind either to the CollectionViewSource itself or to its View property.