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
xmlns:sys="clr-namespace:System;assembly=mscorlib"
<Window.Resources>
<ObjectDataProvider x:Key="aligmnments"
MethodName="GetNames" ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="VerticalAlignment" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<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
|
Pavan | |
|
Commented on 9.September 2009 |
I was just wondering if we could use IValueConverter in order to bind enums.
|
|
|
|
Ravi | |
|
Commented on 9.September 2009 |
I think this is incomplete example. what is TypeName argument in
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="VerticalAlignment" />
</ObjectDataProvider.MethodParameters>
|
|
|
|
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#.
|
|
|
|
tsahi | |
|
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.
|
|
|
|
Anubisascends | |
|
Commented on 20.July 2010 |
Personally, I like this solution for binding enum values:
http://www.ageektrapped.com/blog/the-missing-net-7-displaying-enums-in-wpf/
This allows you to handle localization an more 'user-friendly' display values.
|
|
|
|
tesdt | |
|
Commented on 21.March 2011 |
test
|
|
|
|