排序与enum的ObservableCollection绑定的组合框项
本文关键字:组合 绑定 ObservableCollection enum 排序 | 更新日期: 2023-09-27 18:07:13
我有一个简单的组合框:
<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>();
其中'ElementTypes'是枚举,集合中填充了所有枚举值。例子:
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)二次解
elementTypes = new ObservableCollection<UndrawnElementTypes>(elementTypes.OrderBy(i => i));
elementTypesComboBox.ItemsSource = elementTypes;
这些都不起作用。我做错了什么?
使用OrderBy()
中的ToString()
按字母顺序对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();