我的新应用程序出了问题:
我已将ComboBox的DataSource设置为枚举,因此ComboBox显示枚举的所有成员。好!
但是现在我想更改显示的文本,而不是ComboBox的值。
这是DataSource集:
CbCategory.DataSource = Enum.GetValues(typeof (ConversionCategories.Categorys));
这就是枚举:
public enum Categorys
{
Acceleration,
Area,
Energy,
Frequency,
Length,
Mass,
Time,
Velocity,
Volume,
}
现在例如我希望“Velocity”显示为“Speed”,但值必须相同。
P.S:我不使用WPF。
答案 0 :(得分:1)
您可以创建一个字典,将每个枚举值映射到显示字符串,并使用该字典作为组合框的数据源:
SortedDictionary<Categorys, string> catergoryDictionary = new SortedDictionary<Categorys, string>
{
{Categorys.Acceleration, "Acceleration"},
{Categorys.Area, "Area"},
{Categorys.Velocity, "Speed"}
};
CbCategory.DataSource = new BindingSource(catergoryDictionary, null);
CbCategory.ValueMember = "Key";
CbCategory.DisplayMember = "Value";
答案 1 :(得分:1)
请使用词典。
Dictionary<Categorys, string> catergoryDisplay = new Dictionary<Categorys, string>
{
{Categorys.Velocity, "Speed"}
};
CbCategory.DataSource = new BindingSource(catergoryDisplay , null);
CbCategory.ValueMember = "Key";
CbCategory.DisplayMember = "Value";
请尝试此代码。
答案 2 :(得分:0)
如果该值只能转换为Categorys
,您可以执行以下操作:
public enum Categorys
{
Acceleration,
Area,
Energy,
Frequency,
Length,
Mass,
Time,
Velocity,
Volume
}
private static readonly string[] DisplayNames = new string[]
{
"Acceleration",
"Area",
"Energy",
"Frequency",
"Length",
"Mass",
"Time",
"Speed",
"Volume"
};
private class CategoryItem
{
private Categorys Category;
private string DisplayName;
public CategoryItem(Categorys category, string display_name)
{
Category = category;
DisplayName = display_name;
}
public override string ToString()
{
return DisplayName;
}
public static implicit operator Categorys(CategoryItem item)
{
return item.Category;
}
}
private void Form1_Load(object sender, EventArgs e)
{
List<CategoryItem> items = new List<CategoryItem>();
int i = 0;
foreach (var category in Enum.GetValues(typeof(Categorys)))
items.Add(new CategoryItem((Categorys)category, DisplayNames[i++]));
CbCategory.DataSource = items;
}
然后可以通过以下方式访问该值:
Categorys category = (Categorys)(CategoryItem)CbCategory.SelectedItem;
也许你可以将它包装在getter或类方法中,如:
public Categorys SelectedCategory
{
get { return (Categorys)(CategoryItem)CbCategory.SelectedItem; }
}