Search code examples
c#wpfcomboboxdatagrid

Getting data in List into DataGrid ComboBox


I am having trouble getting items from a list to a combobox column in a datagrid in WPF. This is new to me so any help would be greatly appreciated. It seems there are many ways to do it but I haven't been able to get any of them to work.

'''

                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Positionname}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>

                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <ComboBox x:Name="poscombo Loaded="comboposloaded"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
            
            </DataGridTemplateColumn>

List with Data in the code behind

 List<Positions> PositionList = new List<Positions>();

UPDATE: I ended up adding a loading event to pull the list as the itemsource. The question now is how to get the selected value from combobox back into the text block?

C# Added to get combo loaded.

    private void comboposloaded(object sender, RoutedEventArgs e)
    {
        ComboBox cmb = (ComboBox)sender;
        cmb.ItemsSource = PositionList;
        cmb.DisplayMemberPath = "info";
        cmb.SelectedValuePath = "psnme";

    }

Solution

  • The question now is how to get the selected value from combobox back into the text block?

    Bind the psnme property of the Positions object to the Positionname property of the data object:

    <ComboBox x:Name="poscombo" Loaded="comboposloaded"
              SelectedValue="{Binding Positionname, UpdateSourceTrigger=PropertyChanged}"/>