How to bind an enumeration (enum) to a WPF/Xaml ComboBox

February 16th, 2012 by admin Leave a reply »

You may already know this, but if you don’t I hope it is of some help to somebody out there looking to do this in their code. If you have an enum or enumeration and you simply want to have it as a choice in your UI and also want to bind it to a property on your View Model, I have attached the code to do this below, check it out.

public enum Enum {
        none, 
        Choice1, 
        Choice2
    }

<UserControl.Resources>
        <ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type sys:Enum}" x:Key="odp">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="vm:Enum" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </UserControl.Resources>

<ComboBox ItemsSource="{Binding Source={StaticResource odp}}" IsSynchronizedWithCurrentItem="true" SelectedItem="{Binding PropertyToBindTo, Mode=TwoWay}" Width="100"/>

I am using a UserControl in my example but a standard Xaml window would work as well. Notice also that the key is named as so (x:Key=”odp”) you use that down in your combobox as a static resource since we are placing this in the resources of the user control. If you make a property with the enum as its type you can bind right to the SelectedItem just make sure that you set it to Mode=TwoWay or it may not work. The (ObjectType=”{x:Type sys:Enum}”) simply tells wpf that you are presenting it with an enum type that uses the ‘sys’ namespace. In This line ‘‘ the ‘vm’ is simply the namespace that your Enum sits. I hope this can help somebody out there wanting to implement this type of thing.

Advertisement

Leave a Reply