<Grid
xmlns:local="clr-namespace:SortedEnumInComboBox"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase">
<Grid.Resources>
<CollectionViewSource x:Key="ComparatorsView">
<CollectionViewSource.Source>
<ObjectDataProvider
MethodName="GetNames"
ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:Comparators"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</CollectionViewSource.Source>
</CollectionViewSource>
</Grid.Resources>
<ComboBox
DataContext="{StaticResource ComparatorsView}"
ItemsSource="{Binding}"
VerticalAlignment="Center" />
public enum Comparators
{
MinorThan = -1, Equals = 0, GreaterThan = 1
}
I’m trying to set the enum in a comboBox. In Display must show <, =, and > and SelectedValue will be Comparators value.
I’m not sure if am I use a converter or what?
This solution – which was not created by me – allows you to associate localized strings with enum values.
So assuming we have an enum defined as
Step 1: Add a Windows resource (.resx) file called in this case Resources.resx
Step 2: Add string resources to the file of the form EnumTypeName_EnumName for each enum value, e.g:
Now we need the EnumResourceManagerForLabels attribute which is used by our converter so it know which resource file to use (see usage above):
Now we need the converter:
and finally an example of usage:
Where the view model (using MVVM light) is: