如何使用枚举值的自定义字符串格式设置枚举绑定组合框? [英] How do I have an enum bound combobox with custom string formatting for enum values?
问题描述
在帖子 Enum ToString 中,描述了使用自定义属性 DescriptionAttribute 的方法代码>像这样:
In the post Enum ToString, a method is described to use the custom attribute DescriptionAttribute
like this:
Enum HowNice {
[Description("Really Nice")]
ReallyNice,
[Description("Kinda Nice")]
SortOfNice,
[Description("Not Nice At All")]
NotNice
}
然后,您调用函数 GetDescription
,使用如下语法:
And then, you call a function GetDescription
, using syntax like:
GetDescription<HowNice>(NotNice); // Returns "Not Nice At All"
但这并没有真正帮助我当我想简单地用枚举值填充 ComboBox 时,因为我不能强制 ComboBox 调用 GetDescription
.
But that doesn't really help me when I want to simply populate a ComboBox with the values of an enum, since I cannot force the ComboBox to call GetDescription
.
我想要的有以下要求:
- 读取
(HowNice)myComboBox.selectedItem
将返回选定的值作为枚举值. - 用户应该看到用户友好的显示字符串,而不仅仅是枚举值的名称.因此,用户看到的不是
NotNice
",而是一点儿不好
". - 希望该解决方案只需对现有枚举进行最少的代码更改.
- Reading
(HowNice)myComboBox.selectedItem
will return the selected value as the enum value. - The user should see the user-friendly display strings, and not just the name of the enumeration values. So instead of seeing "
NotNice
", the user would see "Not Nice At All
". - Hopefully, the solution will require minimal code changes to existing enumerations.
显然,我可以为我创建的每个枚举实现一个新类,并覆盖它的 ToString()
,但是对于每个枚举来说,这需要做很多工作,我宁愿避免这种情况.
Obviously, I could implement a new class for each enum that I create, and override its ToString()
, but that's a lot of work for each enum, and I'd rather avoid that.
有什么想法吗?
哎呀,我什至会抛出一个 拥抱 作为赏金:-)
Heck, I'll even throw in a hug as a bounty :-)
推荐答案
您可以编写一个 TypeConverter 来读取指定的属性以在您的资源中查找它们.因此,您可以轻松获得对显示名称的多语言支持.
You could write an TypeConverter that reads specified attributes to look them up in your resources. Thus you would get multi-language support for display names without much hassle.
查看 TypeConverter 的 ConvertFrom/ConvertTo 方法,并使用反射读取枚举字段上的属性.
Look into the TypeConverter's ConvertFrom/ConvertTo methods, and use reflection to read attributes on your enum fields.
这篇关于如何使用枚举值的自定义字符串格式设置枚举绑定组合框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!