I have a ComboBox listing an Enum.
enum StatusEnum {
Open = 1, Closed = 2, InProgress = 3
}
<ComboBox ItemsSource="{Binding StatusList}"
SelectedItem="{Binding SelectedStatus}" />
I want to display localized names for the enum values in English
Open
Closed
In Progress
but also in German (and other languages in the future)
Offen
Geschlossen
In Arbeit
In my ViewModel using
public IEnumerable<StatusEnum> StatusList
{
get
{
return Enum.GetValues(typeof(StatusEnum)).Cast<StatusEnum>();
}
}
only gets me the names of the enum in the code and not the translated ones.
I have general localization in place and can access them using i.e.
Resources.Strings.InProgress
which gets me the translation for the current language.
How can I bind the localization automatically?
You can do using a Attribute for the enum and writing an extension method for the enum. Refer the below code.
I have already posted a similar thing in SO Is it possible to databind to a Enum, and show user-friendly values?
You can't, out of the box.
But you can create an
ObservableList<KeyValuePair<StatusEnum, string>>
property and fill it with your enum/localized text and then bind it to yourComboBox
.As for the string itself:
Getting the Enum string representation with
Enum.GetName
/Enum.GetNames
methods.It's an example of the simple
Enum
to translated string converter.Also you need a
MarkupExtension
which will provide values:Usage:
EDIT: You can make a more complex value converter and markup extension. The
EnumToStringConverter
can useDescriptionAttribute
's to get the translated strings. And theEnumerateExtension
can useTypeConverter.GetStandardValues()
and a converter. This allows to get standard values of the specified type (not onlyEnum
s) and convert them to strings or something another depending on the converter.Example:
EDIT: The more complex solution described above is published on GitHub now.