How to retrieve ComboBox selected value as enum type?

后端 未结 4 1789
情书的邮戳
情书的邮戳 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:56

    Actually, if I would had to do that, I would have built an ObservableCollection previously to the binding (for exemple in the constructor of your view model, using the Enum.GetNames(typeof(EmployeeType)) and then iterating on each values to reparse them as EmployeeType types.

    Once you have your collection set up, you just have to bind it to your ComboBox and then, when selecting an item, you should retreive a type EmployeeType without having to parse it.

    public class VieModel
    {
        private ObservableCollection _internal;
        public ViewModel()
        {
           _internal = new ObservableCollection();
           var tempList =  Enum.GetNames(typeof(EmployeeType));
    
           foreach(var val in tempList)
           {
               EmployeeType et = Enum.Parse(typeof(EmployeeType),val);
               internal.Add(et);
           }
        }
    
        public ObservableCollection EmployeeTypes
        {
           get { return _internal; }
        }
    }
    

    Then set the view model as the data context of your view, and bind your combobox to EmployeeTypes:

     
    

    The selected should return an object of type EmployeeType.

    PS: Sorry about code spelling mistakes, I don't have any C# editor near me right now ;)

提交回复
热议问题