你可以这样做。首先为每个枚举值添加描述
public enum RdiSort
{
[Description("Ascending Description")]
Ascending,
[Description("Descending Description")]
Descending,
[Description("AbsoluteAscending Description")]
AbsoluteAscending,
[Description("AbsoluteDescending Description")]
AbsoluteDescending
}
然后对组合框使用ObjectDataProvider
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:MyEnumerations="clr-namespace:MyEnumerations"
<ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type sys:Enum}"
x:Key="RdiSortValues">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="MyEnumerations:RdiSort" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
使用组合框中的RdiSortValues提供程序并创建一个带有文本块和转换器的数据模板,以查看描述而不是枚举值。
<local:EnumDescriptionConverter x:Key="EnumDescriptionConverter"/>
<ComboBox SelectedItem="{Binding SortType}"
ItemsSource="{Binding Source={StaticResource RdiSortValues}}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource EnumDescriptionConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
最后是转换器。不需要转换回,因为转换程序只在文本块中用于显示。
public class EnumDescriptionConverter : IValueConverter
{
private string GetEnumDescription(Enum enumObj)
{
FieldInfo fieldInfo = enumObj.GetType().GetField(enumObj.ToString());
object[] attribArray = fieldInfo.GetCustomAttributes(false);
if (attribArray.Length == 0)
{
return enumObj.ToString();
}
else
{
DescriptionAttribute attrib = attribArray[0] as DescriptionAttribute;
return attrib.Description;
}
}
object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
RdiSort myEnum = (RdiSort)value;
string description = GetEnumDescription(myEnum);
return description;
}
return null;
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return string.Empty;
}
}