I am encountering a very weird issue. I am trying to apply global styling to several controls within a DataGrid. Most of them work exactly how I would expect them to. However, the styling for the TextBlock never gets applied. Styles for ComboBox, TextBox, Label, and several others all are getting applied to their respective controls, but not the TextBlock. I have simplified the code as much as possible and the issue is still present. I have provided the code sample below.
I need the style to be applied to the TextBlock and I don’t want to have to apply it manually to the TextBlock.
<DataGrid ItemsSource="{Binding Data}" AutoGenerateColumns="False">
<DataGrid.Resources>
<Style TargetType="TextBlock">
<Setter Property="ANY_TEXTBLOCK_PROPERTY" Value="VALUE" />
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTemplateColumn Header="Test">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="Globably Applied" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
More Information:
- Global styles for any control other than
TextBlock(TextBox,ComboBox, etc.) work properly. - Defining the global style inside the
DataTemplatewill work properly. - Directly assigning the style to the
TextBlockusing anx:Keywill work. - Global styles for
DataGridCellusingTextElement.PROPERTYwill get applied to aTextBlock.
While some of these will get the style applied to the TextBlock, they have there own issues. Directly assigning the style or defining the style somewhere within a DataGridColumn will mean that I will have to apply the style more than once. Using the TextElement.PROPERTY on the DataGridCell will apply the style to more than just TextBlock controls and will limit the number of properties that you can set.
So with a bit more digging and a little luck, I discovered that WPF does not apply implicit styles inside templates unless the
TargetTypederives fromControl. SinceTextBlockdoesn’t derive fromControl, its style is not applied. So you either have to manually apply the style to every non-Controlor define the implicit style inside the template.The following MSDN blog post explains it in pretty good detail.
https://learn.microsoft.com/en-us/archive/blogs/wpfsdk/implicit-styles-templates-controls-and-frameworkelements