wpfxamldatagridstylesdatagridcomboboxcolumn

ElementStyle error for DataGridComboBoxColumn in WPF


I'm trying to alter the ElementStyle of a DataGrid ComboBox column. Supposedly the Style is really of type TextBlock when the control is not being edited. So as shown in other examples, I've tried:

<DataGridComboBoxColumn.ElementStyle>
    <Style TargetType="TextBlock">
        <Setter Property="Background" Value="Green" />
    </Style>
</DataGridComboBoxColumn.ElementStyle>

When this is embedded in my DataGridComboBoxColumn definition, I get this weird error message:

'TextBlock' TargetType does not match type of element 'TextBlockComboBox'.

What exactly is a TextBlockComboBox? Or more importantly, how can I get to the ElementStyle, because targeting ComboBox doesn't appear to do anything.


Solution

  • ElementStyle in this case should be the type of ComboBox. We have two types of DataGrid, which it operates - DataGridRow and DataGridCell, the first is a line, the second cell. Therefore, by default, everything is composed of cells of the type DataGridCell not TextBlock's.

    To determine the type of another column, use DataGridTemplateColumn. Therefore DataGridComboBoxColumn maybe is defined as:

    <DataGridTemplateColumn Width="1.5*" IsReadOnly="False" Header="Position2">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <ComboBox x:Name="ComboBoxColumn" />
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    

    With this set can be any type of control.

    In your case, you need to create a style for DataGridCell:

    <Style x:Key="StyleForCell" TargetType="{x:Type DataGridCell}">
        <Setter Property="Background" Value="Green" />
    </Style>
    

    And using like this:

    <DataGridComboBoxColumn x:Name="ComboBoxColumn" 
                            CellStyle="{StaticResource StyleForCell}"
                            Header="Position"
                            SelectedItemBinding="{Binding Position}" />