Bookmark and Share Share...    Subscribe to this feed Feed   About Christian Moser  

How to Bind to Values of an Enum

You cannot directly bind the values of an enum to a WPF list control, because the enum type does not provide a property that returns all values. The only way to get the names is to call the GetNames() method. But how to call a method from XAML?

The trick is to use an ObjectDataProvider, that allows us to specify the name of a method and their parameters and he invokes it from XAML. The result can be used by using a normal data binding

    <ObjectDataProvider x:Key="aligmnments" 
                        MethodName="GetNames" ObjectType="{x:Type sys:Enum}">
            <x:Type TypeName="VerticalAlignment" />
<ComboBox ItemsSource="{Binding Source={StaticResource aligmnments}}" />

Last modified: 2009-06-12 17:42:05
Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments
Commented on 9.September 2009
I was just wondering if we could use IValueConverter in order to bind enums.
Commented on 9.September 2009
I think this is incomplete example. what is TypeName argument in
<x:Type TypeName="VerticalAlignment" />
Christian Moser
Commented on 9.September 2009
Hi Ravi,
it's not incomplete. The ObjectDataProvider calls the static method "GetNames()" on the "Enum" type. This method requires a type object as parameter. This is resolved by the <x:Type /> markup extension. It resolves a type object by a specified name. It's equal to typeof(VerticalAlignment) in C#.
Commented on 29.September 2009
I don't think it's very smart to bind a control to enumeration members at all. For one, it doesn't allow localization of the GUI. And secondly, the user will see things like ReallyBigNumber instead of the string "Really Big Number", which is something he can understand more easily.
Commented on 20.July 2010
Personally, I like this solution for binding enum values:

This allows you to handle localization an more 'user-friendly' display values.
Commented on 21.March 2011

E-Mail (optional)