用枚举说明绑定组合框 [英] Bind Combobox with Enum Description
问题描述
我已经通过Stackoverflow看到了一种简单的方法来用枚举填充组合框:
I have seen through Stackoverflow that there is an easy way to populate a combobox with an Enumeration:
cbTipos.DataSource = Enum.GetValues(typeof(TiposTrabajo));
在我的情况下,我为枚举定义了一些说明:
In my case I have defined some Description for my enumerations:
public enum TiposTrabajo
{
[Description("Programacion Otros")]
ProgramacionOtros = 1,
Especificaciones = 2,
[Description("Pruebas Taller")]
PruebasTaller = 3,
[Description("Puesta En Marcha")]
PuestaEnMarcha = 4,
[Description("Programación Control")]
ProgramacionControl = 5}
这工作得很好,但它显示的是值,而不是描述
我的问题是,我想在组合框中显示枚举的描述(如果它具有描述),或者在没有值的情况下显示值。
如果有必要,我可以为没有说明的值添加说明。
This is working pretty well, but it shows the value, not the description My problem is that I want to show in the combobox the description of the enumeration when it have a description or the value in the case it doesn't have value. If it's necessary I can add a description for the values that doesn't have description. Thx in advance.
推荐答案
尝试以下操作:
cbTipos.DisplayMember = "Description";
cbTipos.ValueMember = "Value";
cbTipos.DataSource = Enum.GetValues(typeof(TiposTrabajo))
.Cast<Enum>()
.Select(value => new
{
(Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute).Description,
value
})
.OrderBy(item => item.value)
.ToList();
要使此功能有效,所有值都必须具有说明,否则您将获得NullReference例外。希望有帮助。
In order for this to work, all the values must have a description or you'll get a NullReference Exception. Hope that helps.
这篇关于用枚举说明绑定组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!