Binding DataGrid ComboBox column to enum?

Apr 14, 2009 at 2:50 PM
Is there a simple example available that shows how to bind the display value of a DataGrid ComboBox column to an enum? I am manually generating my columns, so the auto-generation feature doesn't help me. Thanks for your help.
Apr 14, 2009 at 3:27 PM
It's not exactly what you are looking for, but maybe this can be of help? I found it quite useful for a ComboBox outside of the DataGrid.
Apr 14, 2009 at 5:44 PM
Edited Apr 14, 2009 at 5:56 PM
Found my answer. This problem was a bit more complicated than I expected, so I'll post a fairly detailed description of the solution, which appears pretty much standard.

First, WPF doesn't really automatically recognize enum properties. There is some fairly slick code in the column auto-generator that wires up enums, but if you aren't auto-generating, you are pretty much on your own. Combo boxes suffer from the same problem. So, you can't simply bind your combo box or combo box column to an enum property and expect to get a drop-down list. That takes a little bit of infrastructure, in the form of an ObjectDataProvider (an ODP).

Take a simple User class, with properties for user name, password, and role. Role is an enum that can have one of two values; "User" or "Administrator". I want to bind a combo-box column in my grid to the Role property.

The first thing I need to do is create an ODP as a window resource. The ODP will supply me with the list I need. It will do that by calling the static Enum.GetValues() method on our target enum. Note that we don't have to include the enum in the DataContext for the window or the control; the ODP will access it directly. But we do need to include a namespace declaration in the <Window> tag for the namespace where the enum can be found:


Then, we include the ODP in the <Window.Resources> tag:

    <ObjectDataProvider x:Key="UserRoles" MethodName="GetValues" ObjectType="{x:Type sys:Enum}" >
            <x:Type TypeName="domain:UserRole" />

With that done, we can set the ItemsSource property on our combo-box grid column (or combo box) to the list returned by the ODP:

<dg:DataGridComboBoxColumn Header="Role" Width="*"  ItemsSource="{Binding Source={StaticResource UserRoles}}" 
        SelectedValueBinding="{Binding Path=Role}"  IsReadOnly="false" />

Note that we bind the SelectedValueBinding of the combo-box column to the enum property itself. A combo box binds pretty much the same way.

I hope this helps somebody else down the road! If there is a better way to get this done, please post it as a response.