WPF DataGridComboBoxColumn generated from code

67 Views Asked by At

I am generating a column in combo format from code that is included in an editable datagridview associated with a DataTable.

When I place myself in the cell, the combo with the values ​​appears, but I can't get the SelectedValue to be displayed in the cell. In fact, in the initial data load, that cell no longer shows the value of the data list (I receive the values, 0,1, or 2 in the data table), and I suppose that somehow I have not known how to create the binding necessary.

protected override void OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e)
        {
           if ( e.PropertyName == "combocolumn") {
                    var cb = new DataGridComboBoxColumn();
                    cb.Header = "ColumnCombo";
                    cb.Visibility =  Visibility.Visible;
                    cb.IsReadOnly = false;
                    cb.DisplayMemberPath = "Descripcion";
                    cb.SelectedValuePath = "Codigo";
                    cb.ItemsSource = Datos;
                    
                    e.Column = cb;
                    
                  }
            
            
            base.OnAutoGeneratingColumn(e);
        }

// ===> datos ...
 public class DatosCombo
    {
        public int Codigo { get; set; }
        public string Descripcion { get; set; }
        
    }


 private List<DatosCombo> Datos= new List<DatosCombo>()
        {
            new DatosCombo() { Codigo = 0,Descripcion="Dato1"},
            new DatosCombo() { Codigo = 1,Descripcion="Dato2"},
            new DatosCombo() { Codigo = 2,Descripcion="Dato3"}
        };
1

There are 1 best solutions below

0
Jordi Pujol Carme On

In case it is useful for more people, I already solved the problem by adding :

cb.SelectedValueBinding = new System.Windows.Data.Binding("DatosCombo");