Related: Get enum from enum attribute
I want the most maintainable way of binding an enumeration and it\'s associated localized string values to something.
I've to use it in WPF here is how I achieve it
First of all you need to define an attribute
public class LocalizedDescriptionAttribute : DescriptionAttribute
{
private readonly string _resourceKey;
private readonly ResourceManager _resource;
public LocalizedDescriptionAttribute(string resourceKey, Type resourceType)
{
_resource = new ResourceManager(resourceType);
_resourceKey = resourceKey;
}
public override string Description
{
get
{
string displayName = _resource.GetString(_resourceKey);
return string.IsNullOrEmpty(displayName)
? string.Format("[[{0}]]", _resourceKey)
: displayName;
}
}
}
You can use that attribute like this
public enum OrderType
{
[LocalizedDescription("DineIn", typeof(Properties.Resources))]
DineIn = 1,
[LocalizedDescription("Takeaway", typeof(Properties.Resources))]
Takeaway = 2
}
Then Define a converter like
public class EnumToDescriptionConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo language)
{
var enumValue = value as Enum;
return enumValue == null ? DependencyProperty.UnsetValue : enumValue.GetDescriptionFromEnumValue();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo language)
{
return value;
}
}
Then in your XAML