ElementStyle Error for DataGridComboBoxColumn in WPF

I am trying to change the ElementStyle of a DataGrid ComboBox column. Presumably, the style is indeed of type TextBlock when the control is not being edited. So, as shown in other examples, I tried:

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

When this is embedded in my definition of a DataGridComboBoxColumn , I get this strange error message:

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

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

+4
source share
2 answers

ElementStyle in this case must be of type ComboBox . We have two types of DataGrid that it uses - DataGridRow and DataGridCell , the first is a row, the second cell. Therefore, by default, everything consists of cells of type DataGridCell not TextBlock's .

To determine the type of another column, use a DataGridTemplateColumn . Therefore, a DataGridComboBoxColumn can be defined as:

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

There can be any type of control with this kit.

In your case, you need to create a style for the 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}" /> 
+2
source

TextBlockComboBox is an internal type of DataGridComboBoxColumn . I also don’t know how to get this style, but you can trick DataGridComboBoxColumn.ElementStyle with ComboBox style that looks like 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 the globally defined TextBlock style, defined elsewhere, and bind the Text property to the ComboBox . Finally, you can use the style like this:

 <DataGridComboBoxColumn ElementStyle="{StaticResource TextBlockComboBoxStyle}" EditingElementStyle="{StaticResource {x:Type ComboBox}}" /> 

EditingElementStyle in this case is again the globally defined ComboBox style defined elsewhere.

+3
source

Source: https://habr.com/ru/post/1497499/


All Articles