简体   繁体   English

使用空格在ComboBox中显示枚举

[英]Display enum in ComboBox with spaces

I have an enum, example: 我有一个枚举,例如:

enum MyEnum
{
My_Value_1,
My_Value_2
}

With : 用:

comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));

But now my question: How can I replace the "_" with " " so that it becomes items with spaces instead of underscores? 但现在我的问题是:如何将“_”替换为“”,以便它成为带空格而不是下划线的项目? And that a databound object still works 并且数据绑定对象仍然有效

If you have access to the Framework 3.5, you could do something like this: 如果您可以访问Framework 3.5,则可以执行以下操作:

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

This will return you an IEnumerable of an anonymous type, that contains a Value property, that is the enumeration type itself, and a Text property, that will contain the string representation of the enumerator with the underscores replaced with space. 这将返回一个匿名类型的IEnumerable,它包含一个Value属性,即枚举类型本身,以及一个Text属性,它将包含枚举数的字符串表示形式,下划线用空格替换。

The purpose of the Value property is that you can know exactly which enumerator was chosen in the combo, without having to get the underscores back and parse the string. Value属性的目的是您可以确切地知道在组合中选择了哪个枚举器,而不必返回下划线并解析字符串。

If you are able to modify the code defining the enum, so you could add attributes to the values without modifying the actual enum values, then you could use this extension method. 如果您能够修改定义枚举的代码,那么您可以在不修改实际枚举值的情况下向值添加属性,那么您可以使用此扩展方法。

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

Try this... 试试这个...

comboBox1.DataSource = Enum.GetValues(typeof(MyEnum))
                           .Cast<MyEnum>()
                           .Select(e => new { Value = e, Description = e.ToString().Replace("_"," ") })
                           .ToList();
comboBox1.DisplayMember = "Description";
comboBox1.ValueMember = "Value";

...although, I would be more inclined to use a "Description" attribute (as per Steve Crane's answer) . ...虽然,我更倾向于使用“描述”属性(根据Steve Crane的回答)

Fill the combobox manually and do a string replace on the enum. 手动填充组合框并在枚举上进行字符串替换。

Here is exactly what you need to do: 这正是您需要做的:

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("_", " "));
}

To set the selected item of the combobox do the following: 要设置组合框的选定项目,请执行以下操作:

comboBox1.SelectedItem = MyEnum.My_Value_2.ToString().Replace("_", " ");

I like Kelsey's answer although I would use another variable other than 'e' such as 'en' so the answer can be used in event handlers with less hassle; 我喜欢Kelsey的答案,虽然我会使用除“e”之外的其他变量,例如'en',所以答案可以用在事件处理程序中,而不用麻烦; 'e' in event handlers tends to be the EventArgs argument. 事件处理程序中的'e'往往是EventArgs参数。 As for the LINQ and IEnumerable approach, it seems to me to be more complex and difficult to adapt for non-WPF ComboBox es with .NET 3.5 对于LINQ和IEnumerable方法,在我看来,使用.NET 3.5非常复杂且难以适应非WPF ComboBox es

If you're using .NET 3.5, you could add this extension class: 如果您使用的是.NET 3.5,则可以添加此扩展类:

public static class EnumExtensions {

    public static List<string> GetFriendlyNames(this Enum enm) {
        List<string> result = new List<string>();
        result.AddRange(Enum.GetNames(enm.GetType()).Select(s => s.ToFriendlyName()));
        return result;
    }

    public static string GetFriendlyName(this Enum enm) {
        return Enum.GetName(enm.GetType(), enm).ToFriendlyName();
    }

    private static string ToFriendlyName(this string orig) {
        return orig.Replace("_", " ");
    }
}

And then to set up your combo box you'd just do: 然后设置你刚刚做的组合框:

MyEnum val = MyEnum.My_Value_1;
comboBox1.DataSource = val.GetFriendlyNames();
comboBox1.SelectedItem = val.GetFriendlyName();

This should work with any Enum. 这适用于任何枚举。 You'd have to make sure you have a using statement for the namespace that includes the EnumExtensions class. 您必须确保您具有包含EnumExtensions类的命名空间的using语句。

I think that this is not very good idea to map internal enum name into user space. 我认为将内部枚举名称映射到用户空间并不是一个好主意。 What if you refactor your enum value? 如果你重构你的枚举值怎么办? So I suggest you to take a look at this article (Localizing .NET Enums) . 所以我建议你看一下这篇文章(本地化.NET Enums) Using technique described in this article, you can not only replace '_' with spaces, but also make different enum representation for different languages (using resources). 使用本文中描述的技术,您不仅可以用空格替换'_',还可以为不同的语言(使用资源)创建不同的枚举表示。

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

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