How do I bind the values of an enum to a ComboBox ?

Platform: WPF| Category: ComboBox

ComboBox can be bound to an enum in XAML or in code. The below code shows binding to the ‘Visibility’ enum,

[XAML]

<ObjectDataProvider x:Key='VisibilityList' ObjectType='{x:Type sys:Enum}' MethodName='GetValues'>
	<ObjectDataProvider.MethodParameters>
		<x:TypeExtension TypeName='sys:Visibility'>
	</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

<ComboBox x:Name='ComboBox1' ItemsSource='{Binding Source={StaticResource VisibilityList}}' SelectedIndex='0' />

Same thing in code-behind:

[C#]

// Setup the binding as follows:
comboBox1.ItemsSource = Enum.GetValues(typeof Visibility);

You can retrieve the selected enum value at any time using a simple cast as follows:

[C#]
Visibility visibility = (Visibility)this.myCombo.SelectedItem;

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.