1

I´m trying to bind Data to a DataGridComboBoxColumn.

I already managed to bind the ItemsSource, but the bound value won´t be selected, instead the ComboBox has just nothing selected.

DataGrid:

<DataGrid x:Name="dg" ItemsSource="{Binding}" AutoGenerateColumns="false">
    <DataGrid.Columns>
        <DataGridComboBoxColumn Header="Name" SelectedValueBinding="{Binding name}" ItemsSource="{Binding Source={x:Static K:Material.loadedMaterials}}" DisplayMemberPath="name"/>
        <DataGridTextColumn Header="Name2" Binding="{Binding name}"/>
    </DataGrid.Columns>
</DataGrid>

Material-Class:

public class Material {
    public static List<Material> loadedMaterials;

    static Material() {
        loadedMaterials = new List<Material>();

        loadedMaterials.Add(new Material("TEST1", "", ""));
        loadedMaterials.Add(new Material("TEST2", "", ""));
        loadedMaterials.Add(new Material("TEST3", "", ""));
    }

    public string name { get; set; }
    public string name2 { get; set; }
    public string name3 { get; set; }

    public Material(string n, string n2, string n3) {
        name = n;
        name2 = n2;
        name3 = n3;
    }
}

Main Window:

public partial class MainWindow : Window {
    public System.Collections.ObjectModel.ObservableCollection<Material> mat;

    public MainWindow() {
        InitializeComponent();

        mat = new System.Collections.ObjectModel.ObservableCollection<Material>();
        mat.Add(new Material("TEST1", "TEST1", "TEST1"));

        dg.DataContext = mat;
    }
}

As you can see here, the DropDown is loaded and the Textbox, which has the same data bound, shows it correctly, but the ComboBox is empty.

I´m excpecting TEST1 to be selected and displayed in the ComboBox.

enter image description here

Tim Schmidt
  • 1,297
  • 1
  • 15
  • 30

1 Answers1

4

You have to set SelectedValuePath on your DataGridComboBoxColumn

<DataGridComboBoxColumn Header="Name" SelectedValueBinding="{Binding name}" ItemsSource="{Binding Source={x:Static K:Material.loadedMaterials}}" DisplayMemberPath="name" SelectedValuePath="name"/>
nosale
  • 808
  • 6
  • 14
  • Thats working, thanks. Can you explain whats the difference between those two properties? I just started working with Databindings and thought `SelectedValueBinding` should do the whole trick. – Tim Schmidt Nov 29 '18 at 14:24
  • 2
    @TimSchmidt `SelectedValuePath` and `SelectedValue(Binding)` are always used together as an alternative to `SelectedItem`. `SelectedValuePath` is the path to the property of the `SelectedItem` that is returned by the `SelectedValue`. See also https://stackoverflow.com/questions/4902039/difference-between-selecteditem-selectedvalue-and-selectedvaluepath – nosale Nov 29 '18 at 14:40
  • Ahhh, I see. Thak you for the explanation. :) – Tim Schmidt Nov 29 '18 at 14:47