【问题标题】:Bind Combobox with Enum Description使用枚举描述绑定组合框
【发布时间】:2016-03-11 09:02:01
【问题描述】:

我通过 Stackoverflow 看到有一种简单的方法可以用枚举填充组合框:

cbTipos.DataSource = Enum.GetValues(typeof(TiposTrabajo));

在我的例子中,我为我的枚举定义了一些描述:

 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}

这很好用,但它显示的是价值,而不是描述 我的问题是我想在组合框中显示枚举的描述,当它有描述时,或者在它没有值的情况下显示值。 如果有必要,我可以为没有描述的值添加描述。 提前谢谢。

【问题讨论】:

    标签: c# combobox enums


    【解决方案1】:

    试试这个:

    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 异常。希望对您有所帮助。

    【讨论】:

    • 这非常有用。但是如何将组合框预设为特定项目?
    • 我必须为组合框添加这两行以正确识别 Select() 的 2 个属性: cbTipos.DisplayMember = "Description"; cbTipos.ValueMember = "价值";
    【解决方案2】:

    这是我想出的,因为我还需要设置默认值。

    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;
            }
        }
    }
    

    用法:

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

    其中cmbFileTypeComboBoxFileTypeenum

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-04
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 2012-08-19
      相关资源
      最近更新 更多