这是我的Enum代码:
public enum EmployeeType
{
Manager,
Worker
}
Run Code Online (Sandbox Code Playgroud)
我将初始化ComboBox值,而表单初始化为
combobox1.ItemsSource = Enum.GetValues(typeof(EmployeeType));
Run Code Online (Sandbox Code Playgroud)
现在我想找回的选择的值ComboBox作为EmployeeType枚举,而不是字符串或整数等
任何帮助表示赞赏.
Tim*_*Tim 11
EmployeeType selected = (EmployeeType)combobox1.SelectedItem;
Run Code Online (Sandbox Code Playgroud)
您可能希望首先检查null(无选择).
为了完整起见,这是我设置的示例程序.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>
Run Code Online (Sandbox Code Playgroud)
和代码隐藏:
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());
}
}
}
}
Run Code Online (Sandbox Code Playgroud)