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.
TextBlockComboBox
is an internal type to DataGridComboBoxColumn
. I also don't know how to get that type styled but you can trick DataGridComboBoxColumn.ElementStyle
by using a ComboBox
style that looks like a TextBlock
:
<Style x:Key="TextBlockComboBoxStyle"
TargetType="{x:Type ComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ComboBox}">
<TextBlock Text="{TemplateBinding Text}"
Style="{StaticResource {x:Type TextBlock}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
In the above style I use a globally-defined TextBlock
style defined elsewhere and bind the Text
property of the ComboBox
. Finally you can use the style like so:
<DataGridComboBoxColumn ElementStyle="{StaticResource TextBlockComboBoxStyle}"
EditingElementStyle="{StaticResource {x:Type ComboBox}}" />
The EditingElementStyle
in this case is again a globally-defined ComboBox
style defined elsewhere.
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}" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With