自定义组合框的枚举名称

本文关键字:枚举 组合 自定义 | 更新日期: 2023-09-27 18:15:23

我有一个命名空间,我在其中声明了一个枚举,如下所示:

namespace IXMSoft.Business.SDK.Data
{
using System;
public enum BaudRate
{
    BR115200 = 7,
    BR19200 = 4,
    BR230400 = 8,
    BR2400 = 1,
    BR38400 = 5,
    BR4800 = 2,
    BR57600 = 6,
    BR9600 = 3
  }
}

当我在另一个名称空间中的组合框中检索这些值时,使用语句

comboBox1.Items.Add(BaudRate.BR5700);

显示的值,例如

"BR5700"

我想要remove BR in front and just want to display the value as "5700"。我该怎么办?

自定义组合框的枚举名称

使用DescriptionAttribute和适当的扩展方法将其读出

public enum BaudRate
{
    [Description("115200 kb")]
    BR115200 = 7,
    [Description("19200 kb")]
    BR19200 = 4,
    [Description("230400 kb")]
    BR230400 = 8,
    [Description("2400 kb")]
    BR2400 = 1,
    [Description("115200 kb")]
    BR38400 = 5,
    [Description("4800 kb")]
    BR4800 = 2,
    [Description("57600 kb")]
    BR57600 = 6,
    [Description("9600 kb")]
    BR9600 = 3
}

扩展方法:

public static class EnumExtension
{
    /// <summary>
    /// Gets the string of an DescriptionAttribute of an Enum.
    /// </summary>
    /// <param name="value">The Enum value for which the description is needed.</param>
    /// <returns>If a DescriptionAttribute is set it return the content of it.
    /// Otherwise just the raw name as string.</returns>
    public static string Description(this Enum value)
    {
        if (value == null)
        {
            throw new ArgumentNullException("value");
        }
        string description = value.ToString();
        FieldInfo fieldInfo = value.GetType().GetField(description);
        DescriptionAttribute[] attributes =
           (DescriptionAttribute[])
         fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attributes != null && attributes.Length > 0)
        {
            description = attributes[0].Description;
        }
        return description;
    }
    /// <summary>
    /// Creates an List with all keys and values of a given Enum class
    /// </summary>
    /// <typeparam name="T">Must be derived from class Enum!</typeparam>
    /// <returns>A list of KeyValuePair&lt;Enum, string&gt; with all available
    /// names and values of the given Enum.</returns>
    public static IList<KeyValuePair<Enum, string>> ToList<T>() where T : struct
    {
        var type = typeof(T);
        if (!type.IsEnum)
        {
            throw new ArgumentException("T must be an enum");
        }
        return (IList<KeyValuePair<Enum, string>>)
                Enum.GetValues(type)
                    .OfType<Enum>()
                    .Select(e => new KeyValuePair<Enum, string>(e, e.Description()))
                    .ToArray();
    }
    public static T GetValueFromDescription<T>(string description) where T : struct
    {
        var type = typeof(T);
        if(!type.IsEnum)
        {
            throw new ArgumentException("T must be an enum");
        }
        foreach(var field in type.GetFields())
        {
            var attribute = Attribute.GetCustomAttribute(field,
                typeof(DescriptionAttribute)) as DescriptionAttribute;
            if(attribute != null)
            {
                if(attribute.Description == description)
                {
                    return (T)field.GetValue(null);
                }
            }
            else
            {
                if(field.Name == description)
                {
                    return (T)field.GetValue(null);
                }
            }
        }
        throw new ArgumentOutOfRangeException("description");
        // or return default(T);
    }
}

在和,你可以简单地通过调用

将它应用到你的组合框
var list = EnumExtension.ToList<BaudRate>();
myComboBox.DataSource = list;
myComboBox.ValueMember = "Key";
myComboBox.DisplayMember = "Value";

示例与string.replace:

BaudRate.BR115200.ToString().Replace("BR","");

子字符串的例子:

BaudRate.BR115200.ToString().Substring(2);

从enum名称中删除BR似乎是最合乎逻辑的做法。如果枚举本身命名为BaudRate,则BR是多余的。假设它出现在每个值上,它不会给值名增加任何描述性的能力。并且给定枚举值总是以枚举名称为前缀,结果将始终是明确的(BaudRate.9600而不是BaudRate.BR9600)。

如果你不能/不想这样做,那么你需要在每个值上运行一个BaudRate.XXX.ToString().Substring(2),然后添加以删除前两个字符。

public enum BaudRate
{
    BR115200 = 7,
    BR19200 = 4,
    BR230400 = 8,
    BR2400 = 1,
    BR38400 = 5,
    BR4800 = 2,
    BR57600 = 6,
    BR9600 = 3
  }
}
foreach (string name in Enum.GetNames(BaudRate))
{
    cmbEnum.Items.Add(name.Replace("BR",""));
}

将您的组合框定义为如下所示:

<combobox>
   <ComboBoxItem>--</ComboBoxItem>
   <ComboBoxItem>2400</ComboBoxItem>
   <ComboBoxItem>4800</ComboBoxItem>
   <ComboBoxItem>9600</ComboBoxItem>
   <ComboBoxItem>19200</ComboBoxItem> // and soo on
</combobox>
并将Enum绑定到组合框