Saturday, May 24, 2014

Enumeration in WPF/XAML

Enumeration types  can be set by the keyword enum. Often it is needed to view all values of the enumeration. The following example shows how this can be done by setting all values to a ComboBox, so that it can be selected for further actions.

First I have defined an enum.

public enum State

To show all Enum values in a ComboBox I have set the namespace of mscorlib to get Enum and the namespace of the local assembly to get then enum State.


Then I have defined an ObjectDataProvider to get all State values.

        <ObjectDataProvider x:Key="StateValues"
                        ObjectType="{x:Type sys:Enum}"
                <x:Type TypeName="local:State" />

The ObjectDataProvider is referenced by the defined x:Key in the ItemsSource of the ComboBox.

        <ComboBox ItemsSource="{Binding Source={StaticResource StateValues}}"
                  SelectedItem="{Binding SelectedStateValue}"/>

Instead of setting an ObjectDataProvider in the XAML View, it is possible to set an Array in code-behind or in the ViewModel.

StateEnums = Enum.GetNames(typeof(State));

public Array StateEnums

The Array is then binded to the ItemsSource of the ComboBox.

        <ComboBox ItemsSource="{Binding StateEnums}"
                  SelectedItem="{Binding SelectedStateEnum}" />

No comments:

Post a Comment