Skip to content

Instantly share code, notes, and snippets.

@voyce
Created September 16, 2013 09:14
Show Gist options
  • Save voyce/6578336 to your computer and use it in GitHub Desktop.
Save voyce/6578336 to your computer and use it in GitHub Desktop.
WPF EnumItemsSource
/// <summary>
/// Allows us to use enum values as a data source; e.g. for providing as an ItemsSource
/// on a combo box control for user selection.
/// </summary>
public class EnumItemsSource : Collection<String>, IValueConverter
{
Type _type;
IDictionary<Object, Object> _valueToNameMap;
IDictionary<Object, Object> _nameToValueMap;
public Type Type
{
get { return _type; }
set
{
if (!value.IsEnum)
// ReSharper disable LocalizableElement
throw new ArgumentException("Type is not an enum.", "value");
// ReSharper restore LocalizableElement
_type = value;
Initialize();
}
}
public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
{
return _valueToNameMap != null ? _valueToNameMap[value] : null;
}
public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture)
{
if (value == null) return null;
return _nameToValueMap != null ? _nameToValueMap[value] : null;
}
void Initialize()
{
_valueToNameMap = _type
.GetFields(BindingFlags.Static | BindingFlags.Public)
.ToDictionary(fi => fi.GetValue(null), GetDescription);
_nameToValueMap = _valueToNameMap
.ToDictionary(kvp => kvp.Value, kvp => kvp.Key);
Clear();
foreach (var name in _nameToValueMap.Keys)
Add(name as string);
}
static Object GetDescription(FieldInfo fieldInfo)
{
var descriptionAttribute =
(DescriptionAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute));
return descriptionAttribute != null ? descriptionAttribute.Description : fieldInfo.Name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment