如何使用枚举绑定组合框与枚举值自定义字符串格式? [英] How do I have an enum bound combobox with custom string formatting for enum values?

查看:129
本文介绍了如何使用枚举绑定组合框与枚举值自定义字符串格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

枚举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 ,而是会看到 Not Nice At All

  • 希望解决方案将需要对现有枚举进行最少的代码更改。

  • 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.

任何想法?

嘿,我甚至会扔一个 hug 作为赏金: - )

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆