How to Bind an Enum to a ComboBox in C#

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

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

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

Note: If you are using Windows Forms, use the 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 it 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 a full sample.


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.