Further to Adam Markowitz's answer, here is a general purpose way of (relatively) simply setting the ItemSource
values of a combobox to be enums
, while showing the 'Description' attribute to the user. (You'd think everyone would want to do this so that it would be a .NET one liner, but it just isn't, and this is the most elegant way I've found).
First, create this simple class for converting any Enum value into a ComboBox item:
public class ComboEnumItem {
public string Text { get; set; }
public object Value { get; set; }
public ComboEnumItem(Enum originalEnum)
{
this.Value = originalEnum;
this.Text = this.ToString();
}
public string ToString()
{
FieldInfo field = Value.GetType().GetField(Value.ToString());
DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
return attribute == null ? Value.ToString() : attribute.Description;
}
}
Secondly in your OnLoad
event handler, you need to set the source of your combo box to be a list of ComboEnumItems
based on every Enum
in your Enum
type. This can be achieved with Linq. Then just set the DisplayMemberPath
:
void OnLoad(object sender, RoutedEventArgs e)
{
comboBoxUserReadable.ItemsSource = Enum.GetValues(typeof(EMyEnum))
.Cast<EMyEnum>()
.Select(v => new ComboEnumItem(v))
.ToList();
comboBoxUserReadable.DisplayMemberPath = "Text";
comboBoxUserReadable.SelectedValuePath= "Value";
}
Now the user will select from a list of your user friendly Descriptions
, but what they select will be the enum
value which you can use in code.
To access the user's selection in code, comboBoxUserReadable.SelectedItem
will be the ComboEnumItem
and comboBoxUserReadable.SelectedValue
will be the EMyEnum
.