Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Thursday, July 19, 2012

How to Bind to Values of an Enum

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}}" />

No comments:

Post a Comment