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
{
    Unknown,
    Idle,
    WaitingForInput, 
    NoDisplayState
}

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.

xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:EnumExample"

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

    <Window.Resources>
        <ObjectDataProvider x:Key="StateValues"
                        ObjectType="{x:Type sys:Enum}"
                        MethodName="GetValues">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="local:State" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>

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
{
    get;
    set;
}

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

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


No comments:

Post a Comment