How to retrieve ComboBox selected value as enum type?

后端 未结 4 1814
情书的邮戳
情书的邮戳 2021-01-17 01:30

This is my Enum code:

public enum EmployeeType
{
    Manager,
    Worker
}

I will initialize ComboBox values whil

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-17 01:55

    EmployeeType selected = (EmployeeType)combobox1.SelectedItem;
    

    You might want to check for null (no selection) first though.

    For completeness, here was the sample program I set up. The XAML:

    
        
            
                
                
            
            
            

    and the code-behind:

    using System;
    using System.Windows;
    
    namespace WpfApplication1
    {
        /// 
        /// Interaction logic for MainWindow.xaml
        /// 
        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());
                }
            }
        }
    }
    

提交回复
热议问题