In a previous post I created a markup extension which could be used to bind an Enum’s values to an ItemsControl. Now what if we want those values to be localized? The following is a little trick I use to solve this problem.
My translations are stored in .NET resources. When I add a resource representing an Enum value I use the naming convention <EnumName>_<EnumValueName> for the key.
public enum DevicePointFormat
{
Binary,
Decimal,
Hex
}
I have a Value Converter that converts an Enum value to a resource string.
public class LocalizeEnumValue : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
var enumType = value.GetType();
var key = String.Format(CultureInfo.InvariantCulture, "{0}_{1}",
enumType.Name, Enum.GetName(enumType, value));
return MyResources.ResourceManager.GetString(key);
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
Now imagine we have a ComboBox bound to the values of the DevicePointFormat Enum. We can set the ItemTemplate attribute to a custom DataTemplate which invokes the LocalizeEnumValue converter on the EnumValue and displays the string in a TextBlock.
<Window.Resources>
<src:LocalizeEnumValue x:Key="LocalizeEnumValueConverter" />
<DataTemplate x:Key="LocalizedEnumDataTemplate" DataType="{x:Type s:Enum}">
<TextBlock Text="{Binding Converter={StaticResource LocalizeEnumValueConverter}}" />
</DataTemplate>
</Window.Resources>
<StackPanel>
<ComboBox ItemsSource="{Binding Source={src:EnumValues {x:Type src:DevicePointFormat}}}"
ItemTemplate="{StaticResource LocalizedEnumDataTemplate}" />
</StackPanel>