Search code examples
wpfcombobox

Add placeholder DataGrid item after ComboBox selection


I have a WPF DataGrid with a possibility of add new rows (CanUserAddRows="True"). One of my columns is a ComboBox. With the following code I can bind data to this ComboBox:

<DataGridTemplateColumn Header="Validator" MinWidth="150">
   <DataGridTemplateColumn.CellTemplate>
      <DataTemplate>
         <ComboBox ItemsSource="{Binding DataContext.ValidatorVariables, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}, UpdateSourceTrigger=PropertyChanged}"
                      SelectedItem="{Binding SelectedValidatorVariable, UpdateSourceTrigger=PropertyChanged}"
                      IsEnabled="{Binding HasValidator, UpdateSourceTrigger=PropertyChanged}">

If I select a ComboBox item first in a placeholder row, then new item won't be created from this placeholder row. Placeholder row will be added to the item source only if I enter edit mode in a Text column. CheckBox column does not work either, only Text column.

This causes a sideffect:

  1. select ComboBox item
  2. enter edit mode in a Text column

Result: previously selected ComboBox item is cleared

Is there any solution for this scenario?


Solution

  • Any input control, such as for example a ComboBox, is supposed to be put in the CellEditingTemplate. The CellTemplate should contain a TextBlock that displays the currently selected value:

    <DataGridTemplateColumn Header="Validator" MinWidth="150">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding SelectedValidatorVariable}" />
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
        <DataGridTemplateColumn.CellEditingTemplate>
            <DataTemplate>
                <ComboBox ... />
            </DataTemplate>
    </DataGridTemplateColumn>