Reputation: 1838
I have simple combobox:
<ComboBox Grid.Row="0" Grid.Column="1" x:Name="elementTypesComboBox" SelectedValue="{Binding Path=NVP.ElementType, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Stretch" SelectionChanged="ComboBox_SelectionChanged" IsEnabled="{Binding Path=NVP.CEB, Converter={StaticResource CanAddNewElementConverter}, FallbackValue=false}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock VerticalAlignment="Center" Text="{Binding Path=., Mode=OneWay, Converter={StaticResource ElementTypeToStringConverter}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
binded with:
ObservableCollection<ElementTypes> elementTypes = new ObservableCollection<ElementTypes>();
where 'ElementTypes' is enum and collection is filled with all enum values. Example:
public enum ElementTypes
{
E2,
E5,
E6,
E1
}
I just wanna sort my combobox items.
I tried:
1) First sollution:
elementTypesComboBox.Items.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
elementTypesComboBox.Items.SortDescriptions.Add(new SortDescription("Content", ListSortDirection.Ascending));
2) Secund sollution
elementTypes = new ObservableCollection<UndrawnElementTypes>(elementTypes.OrderBy(i => i));
elementTypesComboBox.ItemsSource = elementTypes;
None of this does not work. What I am doing wrong ?
Upvotes: 0
Views: 1321
Reputation: 128061
Use ToString()
in OrderBy()
to sort the ComboBox items alphabetically:
elementTypesComboBox.ItemsSource = Enum.GetValues(typeof(ElementTypes))
.Cast<ElementTypes>()
.OrderBy(e => e.ToString())
.ToList();
You may sort any predefined subset of ElementTypes
the same way:
IEnumerable<ElementTypes> elements = ...
elementTypesComboBox.ItemsSource = elements
.OrderBy(e => e.ToString())
.ToList();
Upvotes: 3