Thursday, January 10, 2013

WPF Bind enum to combo box items.



Bind enum to combo box items.

In order to bind an enum to the data source of any wpf control, we can take advantage of ObjectDataProvider.  Here is an example:


Let’s say we have an enum declared as


namespace SimpleObjectDataSourceExample
{
    public enum DeptEnum { Payroll, Trading, Sales };
}


Here is the xaml to make these enum entries as the items of a combo box.


<Window x:Class="SimpleObjectDataSourceExample.MainWindow2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Sys="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:SimpleObjectDataSourceExample"
        Title="MainWindow2" Height="300" Width="403">
    <Window.Resources>
        <ObjectDataProvider x:Key="deptEnumSource" 
ObjectType="{x:Type Sys:Enum}" MethodName="GetValues" >
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="local:DeptEnum"></x:Type>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
    <Grid>
        <ComboBox Height="23" HorizontalAlignment="Left" Margin="69,68,0,0" Name="comboBox1"
                  VerticalAlignment="Top"
                  Width="156" 
                  ItemsSource="{Binding Source={StaticResource deptEnumSource}}" 
                  >
        </ComboBox>
    </Grid>
</Window>




No comments:

Post a Comment