Search code examples
c#wpfdatagriddatagridcomboboxcolumn

DataGridTemplateColumn with combobox with preselected value


I'm new to WPF and would like to bind a combobox to a datagrid with a DataGridTemplateColumn. I'm not using MVVM. I'm reading a value from a database and would like to show this value as preselected value in the template column. Unfortunately I only found a workaround using a TextBlock as cell template.

Is it also possible to use the Combobox directly as celltemplate and define the preselected Item? I didn't manage to get this to work using SelectedItem, SelectedValue,...

I also tried using datagridcomboboxcolumn, but that was to complicated for a beginner.

XAML:

  <DataGrid x:Name="dataGridComponents" AutoGenerateColumns="False"  CanUserReorderColumns="False" CanUserAddRows="False" IsReadOnly="False" SelectionUnit="Cell" DataGridCell.Selected="DataGridCell_Selected">
      <DataGrid.Columns>
           <DataGridTemplateColumn Header="Dropdown column"  >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>                                                                 
                                <TextBlock Text="{Binding status}" VerticalAlignment="Center" />                                                                
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                    <DataGridTemplateColumn.CellEditingTemplate>
                        <DataTemplate>
                            <ComboBox SelectedValue="{Binding status, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"
                              SelectedValuePath="Content">                                
                                <ComboBoxItem Content="Test" Tag="1" />             
                                <ComboBoxItem Content="Old" Tag="4" />
                            </ComboBox>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellEditingTemplate>
                </DataGridTemplateColumn>
     </DataGrid.Columns>

Code behind:

        DataTable mycomponents = m_db.SelectQuery("Select * FROM test WHERE name='test';");
        dataGridComponents.ItemsSource = mycomponents.DefaultView;            
        dataGridComponents.DataContext = mycomponents.DefaultView;

Solution

  • status refers to a column in the DataTable that holds the currently selected value.

    You need to populate the ComboBox with values of the same type. For example, if status is a string:

    <ComboBox xmlns:sys="clr-namespace:System;assembly=mscorlib"
              SelectedItem="{Binding status}">
        <sys:String>Test</sys:String>
        <sys:String>Old</sys:String>
    </ComboBox>