使用空格在ComboBox中显示枚举

15 c#

我有一个枚举,例如:

enum MyEnum
{
My_Value_1,
My_Value_2
}
Run Code Online (Sandbox Code Playgroud)

用:

comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
Run Code Online (Sandbox Code Playgroud)

但现在我的问题是:如何将"_"替换为"",以便它成为带空格而不是下划线的项目?并且数据绑定对象仍然有效

CMS*_*CMS 16

如果您可以访问Framework 3.5,则可以执行以下操作:

Enum.GetValues(typeof(MyEnum))
    .Cast<MyEnum>()
    .Select(e=> new
                {
                    Value = e,
                    Text = e.ToString().Replace("_", " ")
                });
Run Code Online (Sandbox Code Playgroud)

这将返回一个匿名类型的IEnumerable,它包含一个Value属性,即枚举类型本身,以及一个Text属性,它将包含枚举数的字符串表示形式,下划线用空格替换.

Value属性的目的是您可以确切地知道在组合中选择了哪个枚举器,而不必返回下划线并解析字符串.


Ste*_*ane 6

如果您能够修改定义枚举的代码,那么您可以在不修改实际枚举值的情况下向值添加属性,那么您可以使用此扩展方法.

/// <summary>
/// Retrieve the description of the enum, e.g.
/// [Description("Bright Pink")]
/// BrightPink = 2,
/// </summary>
/// <param name="value"></param>
/// <returns>The friendly description of the enum.</returns>
public static string GetDescription(this Enum value)
{
  Type type = value.GetType();

  MemberInfo[] memInfo = type.GetMember(value.ToString());

  if (memInfo != null && memInfo.Length > 0)
  {
    object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

    if (attrs != null && attrs.Length > 0)
    {
      return ((DescriptionAttribute)attrs[0]).Description;
    }
  }

  return value.ToString();
}
Run Code Online (Sandbox Code Playgroud)


Kel*_*sey 3

手动填充组合框并对枚举进行字符串替换。

这正是您需要做的:

comboBox1.Items.Clear();
MyEnum[] e = (MyEnum[])(Enum.GetValues(typeof(MyEnum)));
for (int i = 0; i < e.Length; i++)
{
    comboBox1.Items.Add(e[i].ToString().Replace("_", " "));
}
Run Code Online (Sandbox Code Playgroud)

要设置组合框的选定项目,请执行以下操作:

comboBox1.SelectedItem = MyEnum.My_Value_2.ToString().Replace("_", " ");
Run Code Online (Sandbox Code Playgroud)