Search code examples
c#wpfcomboboxdatagriddatagridcomboboxcolumn

Binding DataGridComboBoxColumn to Object


I'm trying to bind a Combobox to an object within a datagrid with little success.

Object.cs:

public class Object {

public static IEnumerable<string> Colors => new List<string> {"Red", "Green", "Blue"}

}

public string Color {
get => color;
set => color = value;
}

private string Color;

My ViewModel contains a collection of these models, which I'll call Objects.

XAML file:

<DataGrid Name="DataGrid" ItemsSource={Binding Objects}" Style={StaticResource DataGridStyle}">
    <DataGrid.Columns>
        <DataGridComboBoxColumn Header="Test" SelectedValueBinding="{Binding Color, StringFormat=F3, Mode=TwoWay}" ItemsSource="{Binding Colors}"/>
    <DataGrid.Columns/>
<DataGrid/>

Anybody know what I'm doing wrong? Right now, all I see is a blank space where the ComboBox should be. I've tried the following things without success that I suspect might be the issue:

  • Should my list of Colors be in the object itself or my ViewModel? I've tried both, and I've also tried making the property static.
  • Adding DataGridComboBoxColumn.ElementStyle and DataGridComboBoxColumn.EditingElementStyle

Solution

  • This should work:

    <DataGridComboBoxColumn Header="Test"
                            SelectedValueBinding="{Binding Color, StringFormat=F3, Mode=TwoWay}" 
                            ItemsSource="{x:Static local:Object.Colors}"/>
    

    local maps to the namespace where Object is defined:

    xmlns:local="clr-namespace:WpfApp1"