在post Enum ToString中,描述了使用自定义属性DescriptionAttribute
的方法,如下所示:
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
.时,这对我的没有真正的帮助,因为我不能强制ComboBox调用枚举
我想要的有以下要求:
(HowNice)myComboBox.selectedItem
将返回选定的值作为枚举值。NotNice
",而是"Not Nice At All
".进行最少的代码更改
显然,我可以为我创建的每个枚举实现一个新类,并覆盖它的ToString()
,但这对每个枚举来说都是大量的工作,我宁愿避免这样做。
有什么想法吗?
见鬼,我甚至会抛出一个hug作为赏金:-)
发布于 2009-04-28 07:42:49
您可以编写一个TypeConverter来读取指定的属性,以便在资源中查找它们。因此,您可以很容易地获得显示名称的多语言支持。
查看TypeConverter的ConvertFrom/ConvertTo方法,并使用反射读取枚举字段上的属性。
发布于 2009-04-28 07:36:31
ComboBox
拥有您需要的一切:FormattingEnabled
属性,您应该将其设置为true
;Format
事件,您需要在其中放置所需的格式化逻辑。因此,
myComboBox.FormattingEnabled = true;
myComboBox.Format += delegate(object sender, ListControlConvertEventArgs e)
{
e.Value = GetDescription<HowNice>((HowNice)e.Value);
}
发布于 2009-04-28 07:33:25
别!枚举是原语,而不是UI对象--从设计的角度来看,让它们为.ToString()中的UI提供服务是非常糟糕的。您在尝试解决错误的问题:真正的问题是您不希望Enum.ToString()出现在组合框中!
现在,这确实是一个非常可以解决的问题!您可以创建一个UI对象来表示组合框项:
sealed class NicenessComboBoxItem
{
public string Description { get { return ...; } }
public HowNice Value { get; private set; }
public NicenessComboBoxItem(HowNice howNice) { Value = howNice; }
}
然后,只需将该类的实例添加到组合框的Items集合中,并设置这些属性:
comboBox.ValueMember = "Value";
comboBox.DisplayMember = "Description";
https://stackoverflow.com/questions/796607
复制相似问题