一、目的:在开发过程中绑定的枚举不想显示成英文字段怎么办,这里通过TypeConverter的方式来实现绑定的枚举从定义的特性中读取
二、实现
首先定义如下枚举
[TypeConverter(typeof(DisplayEnumConverter))]public enum MyEnum{[Display(Name = "无")]None,[Display(Name = "第一个")]First,[Display(Name = "第二个")]Second,[Display(Name = "第三个")]Third}
其中DisplayEnumConverter是一个TypeConverter,继承自EnumConverter
public class DisplayEnumConverter : EnumConverter{public DisplayEnumConverter(Type type): base(type){}public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType){if (destinationType == typeof(string)){if (value != null){FieldInfo field = value.GetType().GetField(value.ToString());if (field != null){DisplayAttribute[] array = (DisplayAttribute[])field.GetCustomAttributes(typeof(DisplayAttribute), inherit: false);if (array.Length == 0 || string.IsNullOrEmpty(array[0].Name)){return value.ToString();}return array[0].Name;}}return string.Empty;}return base.ConvertTo(context, culture, value, destinationType);}public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value){return base.ConvertFrom(context, culture, value);}}
三、环境
VS2022
四、示例
页面上定义一个ComboxBox并绑定该枚举
<ComboBox ItemsSource="{h:GetEnumSource EnumType={x:Type local:MyEnum}}"/>
对GetEnumSource具体实现参考文章:示例:WPF中绑定枚举到ComboBox的方式-CSDN博客
显示效果如下
五、需要了解的知识点
EnumConverter 类 (System.ComponentModel) | Microsoft Learn
XamlType.TypeConverter Property (System.Xaml) | Microsoft Learn
六、源码地址
GitHub - HeBianGu/WPF-ControlDemo: 示例
GitHub - HeBianGu/WPF-ControlBase: Wpf封装的自定义控件资源库
GitHub - HeBianGu/WPF-Control: WPF轻量控件和皮肤库
七、了解更多
System.Windows.Controls 命名空间 | Microsoft Learn
https://github.com/HeBianGu
HeBianGu的个人空间-HeBianGu个人主页-哔哩哔哩视频