我有简单的组合框:
<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>
绑定:
ObservableCollection<ElementTypes> elementTypes = new ObservableCollection<ElementTypes>();
其中&#39;元素类型&#39;是enum,集合中包含所有枚举值。例如:
public enum ElementTypes
{
E2,
E5,
E6,
E1
}
我只想对我的组合框项目进行排序。
我试过了:
1)第一次溶解:
elementTypesComboBox.Items.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
elementTypesComboBox.Items.SortDescriptions.Add(new SortDescription("Content", ListSortDirection.Ascending));
2)Secund溶液
elementTypes = new ObservableCollection<UndrawnElementTypes>(elementTypes.OrderBy(i => i));
elementTypesComboBox.ItemsSource = elementTypes;
这些都不起作用。我做错了什么?
答案 0 :(得分:2)
使用ToString()
中的OrderBy()
按字母顺序对ComboBox项目进行排序:
elementTypesComboBox.ItemsSource = Enum.GetValues(typeof(ElementTypes))
.Cast<ElementTypes>()
.OrderBy(e => e.ToString())
.ToList();
您可以采用相同的方式对ElementTypes
的任何预定义子集进行排序:
IEnumerable<ElementTypes> elements = ...
elementTypesComboBox.ItemsSource = elements
.OrderBy(e => e.ToString())
.ToList();