C# 在带有空格的 ComboBox 中显示枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1102022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display enum in ComboBox with spaces
提问by
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
但现在我的问题是:如何将“_”替换为“”,使其成为带有空格而不是下划线的项目?并且数据绑定对象仍然有效
回答by Kelsey
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("_", " ");
回答by CMS
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 Valueproperty, that is the enumeration type itself, and a Textproperty, 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 属性的目的是,您可以准确地知道在组合中选择了哪个枚举数,而不必取回下划线并解析字符串。
回答by Luke Sampson
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 语句。
回答by Steve Crane
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();
}
回答by arbiter
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). Using technique described in this article, you can not only replace '_' with spaces, but also make different enum representation for different languages (using resources).
我认为将内部枚举名称映射到用户空间并不是一个好主意。如果重构枚举值会怎样?所以我建议你看看这篇文章 (Localizing .NET Enums)。使用本文中描述的技术,您不仅可以用空格替换“_”,还可以为不同的语言(使用资源)制作不同的枚举表示。
回答by Black Light
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 的回答)。
回答by g_g
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; 'e' in event handlers tends to be the EventArgs
argument.
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
我喜欢 Kelsey 的答案,尽管我会使用除 'e' 以外的另一个变量,例如 'en',因此可以在事件处理程序中使用该答案,而不会那么麻烦;事件处理程序中的“e”往往是EventArgs
参数。至于 LINQ 和IEnumerable
方法,在我看来,ComboBox
使用 .NET 3.5来适应非 WPF es更加复杂和困难