#485 – Binding a ComboBox to an Enumerated Type’s List of Values
February 1, 2012 Leave a comment
You can easily bind a ComboBox (or ListBox) to an enumerated type’s values using an ObjectDataProvider. The ObjectDataProvider allows calling a method and then using the result of the method call as a binding source.
To get the list of values for an enumerated type, we call the Enum.GetValues method, passing in the specific enumerated type. In the example below, we do this in an ObjectDataProvider.
<Window.Resources> <ObjectDataProvider x:Key="dateTimeKindValues" MethodName="GetValues" ObjectType="{x:Type sys:Enum}"> <ObjectDataProvider.MethodParameters> <x:Type TypeName="sys:DateTimeKind"/> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> </Window.Resources>
(This assumes that we’ve defined the sys namespace):
xmlns:sys="clr-namespace:System;assembly=mscorlib"
The ObjectDataProvider is equivalent to the following code:
DateTimeKind[] values = (DateTimeKind[])Enum.GetValues(typeof(DateTimeKind));
We can now use the output of the ObjectDataProvider as a data source for our binding.
<ComboBox Height="25" Width="150" ItemsSource="{Binding Source={StaticResource dateTimeKindValues}}"/>
This gives us a ComboBox that lists the possible values of the DateTimeKind enumerated type.