Cornelius Cornelius - 1 month ago 41
C# Question

UWP ComboBox: ItemsSource population through enum

so I want to populate a combobox items source with the contents on an enum (and obviously retrieve the values later on).

Populating works fine with either of the two following approaches but neither matches what I want to achieve.

comboBox.ItemsSource = Enum.GetValues(typeof(VirtualKey));


I can retrieve the values without issue using a simple (VirtualKey)comboBox.SelectedItem. The problem is, the names in the dropdown menu are all unreadable.
enter image description here

comboBox.ItemsSource = Enum.GetNames(typeof(VirtualKey));


Displays the names as intended but I can't retrieve the value like with the other instruction.

Any ideas how to solve the situation?

Answer

comboBox.ItemsSource = Enum.GetNames(typeof(VirtualKey));

Displays the names as intended but I can't retrieve the value like with the other instruction.

I don't know how are you getting the selected value, but for converting from enum value name to its value, you can use the Enum.Parse(Type, String) method.

Or you can bind the ComboBox.SelectedIndex to your enum variable for example using something like my EnumToIntConverter.