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:
TextBlock
(TextBox
, ComboBox
, etc.) work properly.DataTemplate
will work properly.TextBlock
using an x:Key
will work.DataGridCell
using TextElement.PROPERTY
will get applied to a TextBlock
.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 TargetType
derives from Control
. Since TextBlock
doesn't derive from Control
, its style is not applied. So you either have to manually apply the style to every non-Control
or define the implicit style inside the template.
The following MSDN blog post explains it in pretty good detail.
https://docs.microsoft.com/en-us/archive/blogs/wpfsdk/implicit-styles-templates-controls-and-frameworkelements
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