Search code examples
wpfdata-bindingwpfdatagrid

Bind a DataGridComboBoxColumn to an Enum


I have a simple DataGrid which I want the user to add some rows to. However I want one of the columns to be a ComboBox with it's values taken from an enum.

What's the simplest way of doing this in my XAML?

I've tried following but I get the error "Two-way binding requires Path or XPath"

<Window.Resources>
    <ObjectDataProvider x:Key="myEnumData"
                MethodName="GetValues" 
                ObjectType="{x:Type sys:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="local:MyEnum" />
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>

...

   <DataGrid.Columns>
        <DataGridComboBoxColumn Header="MyHeader" DisplayMemberPath="EnumValue" 
            SelectedItemBinding="{Binding Source={StaticResource myEnumData}}">
        </DataGridComboBoxColumn>
    </DataGrid.Columns>

Solution

  • You are trying to bind the selected item when you (presumably) want to bind the list of available items. Change your binding to this:

    <DataGridComboBoxColumn Header="MyHeader"
            ItemsSource="{Binding Source={StaticResource myEnumData}, Mode=OneWay}">
    </DataGridComboBoxColumn>