简体   繁体   English

使用枚举说明绑定Combobox

[英]Bind Combobox with Enum Description

I have seen through Stackoverflow that there is an easy way to populate a combobox with an Enumeration: 我已经通过Stackoverflow了解到有一种简单的方法可以使用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. Thx提前。

Try this: 试试这个:

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();

In order for this to work, all the values must have a description or you'll get a NullReference Exception. 为了使其工作,所有值必须具有描述,否则您将获得NullReference异常。 Hope that helps. 希望有所帮助。

Here is what I came up with since I needed to set the default as well. 这是我想出来的,因为我也需要设置默认值。

public static void BindEnumToCombobox<T>(this ComboBox comboBox, T defaultSelection)
{
    var list = Enum.GetValues(typeof(T))
        .Cast<T>()
        .Select(value => new
        {
            Description = (Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute)?.Description ?? value.ToString(),
            Value = value
        })
        .OrderBy(item => item.Value.ToString())
        .ToList();

    comboBox.DataSource = list;
    comboBox.DisplayMember = "Description";
    comboBox.ValueMember = "Value";

    foreach (var opts in list)
    {
        if (opts.Value.ToString() == defaultSelection.ToString())
        {
            comboBox.SelectedItem = opts;
        }
    }
}

Usage: 用法:

cmbFileType.BindEnumToCombobox<FileType>(FileType.Table);

Where cmbFileType is the ComboBox and FileType is the enum . 其中cmbFileTypeComboBoxFileTypeenum

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM