使用空格在ComboBox中显示枚举

我有一个枚举,例如:

enum MyEnum { My_Value_1, My_Value_2 } 

用:

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

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

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

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

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

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

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

 ///  /// Retrieve the description of the enum, eg /// [Description("Bright Pink")] /// BrightPink = 2, ///  ///  /// The friendly description of the enum. 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(); } 

手动填充combobox并在枚举上进行字符串替换。

这正是您需要做的:

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

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

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

试试这个…

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

…虽然,我更倾向于使用“描述”属性(根据Steve Crane的回答)

如果您使用的是.NET 3.5,则可以添加此扩展类:

 public static class EnumExtensions { public static List GetFriendlyNames(this Enum enm) { List result = new List(); 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("_", " "); } } 

然后设置你刚刚做的combobox:

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

这适用于任何枚举。 您必须确保包含EnumExtensions类的命名空间的using语句。

我认为将内部枚举名称映射到用户空间并不是一个好主意。 如果你重构你的枚举值怎么办? 所以我建议你看一下这篇文章(本地化.NET Enums) 。 使用本文中描述的技术,您不仅可以用空格替换’_’,还可以为不同的语言(使用资源)创建不同的枚举表示。

我喜欢Kelsey的答案,虽然我会使用除“e”之外的其他变量,例如’en’,所以答案可以用在事件处理程序中,而不用麻烦; 事件处理程序中的’e’往往是EventArgs参数。 对于LINQ和IEnumerable方法,在我看来,使用.NET 3.5更加复杂和难以适应非WPF ComboBox es