使用枚举的ObservableCollection对Combobox项进行排序

时间:2015-08-11 07:22:04

标签: c# wpf sorting combobox observablecollection

我有简单的组合框:

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

这些都不起作用。我做错了什么?

1 个答案:

答案 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();