我怎么有自定义字符串格式化为枚举值枚举绑定组合框? [英] How do I have an enum bound combobox with custom string formatting for enum values?
问题描述
在的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
,使用的语法如下:
GetDescription<HowNice>(NotNice); // Returns "Not Nice At All"
但是,这并不真正帮助我的时,我想简单地填充枚举的值的组合框,因为我不能强迫组合框调用 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
,用户将看到不是很好。在所有
- 我们希望,该解决方案将需要最少code更改现有枚举。
- 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.
任何想法?
哎呀,我甚至会扔在一个<一个href=\"http://stackoverflow.com/questions/795979/retrieve-a-list-of-the-most-popular-get-param-variations-for-a-given-url\">hug作为赏金: - )
Heck, I'll even throw in a hug as a bounty :-)
推荐答案
您可以编写一个读取指定的属性,看看他们在你的资源的类型转换器。因此,你会得到的显示名称多语言支持,没有什么麻烦。
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屋!