use*_*405 7 c# wpf enums combobox
我有一个关于C#和WPF的简单问题.我的问题将在我的尝试后继续:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
foreach (var item in Races)
{
cbRace.Items.Add(item);
}
}
}
enum Races
{
Human=1,
Dwarf,
Elf,
Orc,
Goblin,
Vampire,
Centaur
}
Run Code Online (Sandbox Code Playgroud)
好吧,我的问题是如何将值(例如Human,dwarf,elf ....)添加到组合框中:cbRace?抱歉,我是C#的新手,所以如果有人可以帮助我,我会集会赞赏:),提前谢谢.
小智 20
private void Window_Loaded(object sender, RoutedEventArgs e)
{
foreach (var item in Enum.GetValues(typeof(Races)))
{
cbRace.Items.Add(item);
}
}
enum Races
{
Human = 1,
Dwarf,
Elf,
Orc,
Goblin,
Vampire,
Centaur
}
Run Code Online (Sandbox Code Playgroud)
Crw*_*ryn 16
你应该可以做这样的事情:
cbRace.DataSource = Enum.GetValues(typeof(Races));
Run Code Online (Sandbox Code Playgroud)
有关设置和检索枚举值的更多信息,请查看此答案.
这可能是设置ComboBox项的最简单方法:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
cbRace.ItemsSource = Enum.GetValues(typeof(Races));
cbRace.SelectedIndex = 0;
}
Run Code Online (Sandbox Code Playgroud)
没有必要遍历枚举值,只需设置ItemsSource
属性即可.