[英]Display enum in ComboBox with spaces
我有一个枚举,例如:
enum MyEnum
{
My_Value_1,
My_Value_2
}
用:
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
但现在我的问题是:如何将“_”替换为“”,以便它成为带空格而不是下划线的项目? 并且数据绑定对象仍然有效
如果您可以访问Framework 3.5,则可以执行以下操作:
Enum.GetValues(typeof(MyEnum))
.Cast<MyEnum>()
.Select(e=> new
{
Value = e,
Text = e.ToString().Replace("_", " ")
});
这将返回一个匿名类型的IEnumerable,它包含一个Value属性,即枚举类型本身,以及一个Text属性,它将包含枚举数的字符串表示形式,下划线用空格替换。
Value属性的目的是您可以确切地知道在组合中选择了哪个枚举器,而不必返回下划线并解析字符串。
如果您能够修改定义枚举的代码,那么您可以在不修改实际枚举值的情况下向值添加属性,那么您可以使用此扩展方法。
/// <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();
}
试试这个...
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum))
.Cast<MyEnum>()
.Select(e => new { Value = e, Description = e.ToString().Replace("_"," ") })
.ToList();
comboBox1.DisplayMember = "Description";
comboBox1.ValueMember = "Value";
...虽然,我更倾向于使用“描述”属性(根据Steve Crane的回答) 。
手动填充组合框并在枚举上进行字符串替换。
这正是您需要做的:
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("_", " "));
}
要设置组合框的选定项目,请执行以下操作:
comboBox1.SelectedItem = MyEnum.My_Value_2.ToString().Replace("_", " ");
我喜欢Kelsey的答案,虽然我会使用除“e”之外的其他变量,例如'en',所以答案可以用在事件处理程序中,而不用麻烦; 事件处理程序中的'e'往往是EventArgs
参数。 对于LINQ和IEnumerable
方法,在我看来,使用.NET 3.5非常复杂且难以适应非WPF ComboBox
es
如果您使用的是.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("_", " ");
}
}
然后设置你刚刚做的组合框:
MyEnum val = MyEnum.My_Value_1;
comboBox1.DataSource = val.GetFriendlyNames();
comboBox1.SelectedItem = val.GetFriendlyName();
这适用于任何枚举。 您必须确保您具有包含EnumExtensions类的命名空间的using语句。
我认为将内部枚举名称映射到用户空间并不是一个好主意。 如果你重构你的枚举值怎么办? 所以我建议你看一下这篇文章(本地化.NET Enums) 。 使用本文中描述的技术,您不仅可以用空格替换'_',还可以为不同的语言(使用资源)创建不同的枚举表示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.