Binding an Enum to a ComboBox


The GetValues method of Enum returns an array of objects. We can use this method to convert an enum to an array and bind to a ComboBox in WPF using ItemsSource property.

The following code snippet binds InkCanvasEditingMode enum available in WPF to a ComboBox.

InkEditingModeList.ItemsSource = System.Enum.GetValues(typeof(InkCanvasEditingMode));

Note: If you are using Windows Forms, use DataSource property, instead of ItemsSource.

Now, once we have an enum bound to a ComboBox, we need to the selected item from ComboBox and convert back to the enum. Unfortunately, ComboBox selected item gives us a string. Now we will have to convert back to the string value to an enum value.

For that, we can use Enum.Parse method and cast it to the enumeration. The following code snippet takes the selected value in a ComboBox and converts it back to the enum value.

string str = InkEditingModeList.Items[InkEditingModeList.SelectedIndex].ToString();

InkBoard.EditingMode = (InkCanvasEditingMode)Enum.Parse(typeof(InkCanvasEditingMode),                 InkEditingModeList.Items[InkEditingModeList.SelectedIndex].ToString());

 

Download the attached project for full sample.

Up Next
    Ebook Download
    View all
    Learn
    View all