如何检索ComboBox选择的值作为枚举类型? [英] How to retrieve ComboBox selected value as enum type?
本文介绍了如何检索ComboBox选择的值作为枚举类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的枚举
代码:
public enum EmployeeType
{
Manager,
Worker
}
我将初始化 ComboBox
值,而窗体将其本身初始化为
I will initialize ComboBox
values while form initialize itself as
combobox1.ItemsSource = Enum.GetValues(typeof(EmployeeType));
现在我想检索所选值 ComboBox
as EmployeeType
枚举,不是字符串或整数等。
Now I want to retrieve the selected value of ComboBox
as EmployeeType
enum, not as string or integer, etc.
任何帮助都不胜感激。 >
Any help is appreciated.
推荐答案
EmployeeType selected = (EmployeeType)combobox1.SelectedItem;
您可能希望首先检查null(不选择)。
You might want to check for null (no selection) first though.
为了完整,这里是我设置的示例程序。 XAML:
For completeness, here was the sample program I set up. The XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<ComboBox x:Name="_ComboBox" />
<Button Grid.Row="1" Click="Button_Click" />
</Grid>
</Window>
和代码隐藏:
using System;
using System.Windows;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
_ComboBox.ItemsSource = Enum.GetValues(typeof(Whatever));
}
public enum Whatever
{
One,
Two,
Three,
Four
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (_ComboBox.SelectedItem == null)
{
MessageBox.Show("No Selection");
}
else
{
Whatever whatever = (Whatever)_ComboBox.SelectedItem;
MessageBox.Show(whatever.ToString());
}
}
}
}
这篇关于如何检索ComboBox选择的值作为枚举类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文