Search code examples
wpfdatagridcomboboxcolumn

WPF dynamic DatagridComboboxColumn


I dynamically create a DataGridComboboxColum in the code. This works fine, however when I select an item in the Combobox in the Grid it disappears after i leave the combobox.

Here is the code:

MyDataGrid.ItemsSource = ergList;

DataGridComboBoxColumn cb = new DataGridComboBoxColumn();
cb.ItemsSource = data
cb.Header = "Tag";                  

cb.DisplayMemberPath = "Tag";
MyDataGrid.Columns.Add(cb);

How can i fix this?


Solution

  • You need to bind the selected value in the ComboBox to a property of the item in your ergList:

    MyDataGrid.ItemsSource = ergList;
    
    DataGridComboBoxColumn cb = new DataGridComboBoxColumn();
    cb.ItemsSource = data
    b.Header = "Tag";
    
    cb.DisplayMemberPath = "Tag";
    cb.SelectedValueBinding = new Binding("SomePropertyOfAnItemInErgList");
    MyDataGrid.Columns.Add(cb);
    

    Make sure that the types of the items in the ComboBox and the property to hold the selected value match.