Show Enum Description Instead of Name
If you keep this ItemsSource
you will have to define a custom ItemTemplate
as the DisplayMemberPath
is just a path via which you will not be able to retrieve the description.
As for what the template should look like: You can bind a TextBlock
to the enum value (the current DataContext
) and pipe that through a ValueConverter
using Binding.Converter
. The code would just be some reflection to retrieve the Description
(GetType
, GetCustomAttributes
etc.)
Alternatives are a custom method that return a usable collection right away (and is used in the ObjectDataProvider
) or a custom markup extension which does the same thing.
Method example if we are talking about a ComponentModel.DescriptionAttribute
:
public static class EnumUtility
{
// Might want to return a named type, this is a lazy example (which does work though)
public static object[] GetValuesAndDescriptions(Type enumType)
{
var values = Enum.GetValues(enumType).Cast<object>();
var valuesAndDescriptions = from value in values
select new
{
Value = value,
Description = value.GetType()
.GetMember(value.ToString())[0]
.GetCustomAttributes(true)
.OfType<DescriptionAttribute>()
.First()
.Description
};
return valuesAndDescriptions.ToArray();
}
}
<ObjectDataProvider x:Key="Data" MethodName="GetValuesAndDescriptions"
ObjectType="local:EnumUtility">
<ObjectDataProvider.MethodParameters>
<x:TypeExtension TypeName="local:TestEnum" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<ListBox ItemsSource="{Binding Source={StaticResource Data}}"
DisplayMemberPath="Description"
SelectedValuePath="Value"/>