How to retrieve ComboBox selected value as enum type?

后端 未结 4 1790
情书的邮戳
情书的邮戳 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 02:04

    Try something like this: First assign the combo box to the GetNames method, this will populate the items with the names of the enum rather than the numbers. Then handle the changed event and parse the string back to an enum.

        public enum EmployeeType
        {
            Manaer,
            Worker
        }
    
        public MainWindow()
        {
            InitializeComponent();
            this.combobox1.ItemsSource = Enum.GetNames(typeof(EmployeeType));
            this.combobox1.SelectionChanged += new SelectionChangedEventHandler(combobox1_SelectionChanged);
        }
    
        void combobox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            EmployeeType selection = (EmployeeType)Enum.Parse(typeof(EmployeeType), (string)this.combobox1.SelectedItem);
            this.ResultsTextBlock.Text = selection.ToString();
        }
    

    One thing to add is, you can add the data annotation Display attribute to each enum and write a method that will parse the enum and display the attribute's name property rather than the enum making it more user friendly.

提交回复
热议问题