WPF ControlTemplate breaks style
WPF considers ControlTemplates
to be a boundry, and will not apply implicit styles (styles without an x:Key
) inside of templates.
But there is one exception to this rule: anything that inherits from Control
will apply implicit styles.
So you could use a Label
instead of a TextBlock
, and it would apply the implicit style defined further up your XAML hierarchy, however since TextBlock
inherits from FrameworkElement
instead of Control
, it won't apply the implicit style automatically and you have to add it manually.
My most common way to get around this is to add an implicit style in the ControlTemplate.Resources
that is BasedOn
the existing implicit TextBlock
style
<ControlTemplate.Resources> <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource {x:Type TextBlock}}" /> <ControlTemplate.Resources>
Other common ways of getting around this are:
Place the implicit style in
<Application.Resources>
. Styles placed here will apply to your entire application, regardless of template boundaries. Be careful with this though, as it will apply the style toTextBlocks
inside of other controls as well, like Buttons or ComboBoxes<Application.Resources> <Style TargetType="{x:Type TextBlock}"> <Setter Property="Foreground" Value="Green" /> </Style></Application.Resources>
Use a
Label
instead of aTextBlock
since it's inherited fromControl
, so will apply implicit Styles defined outside theControlTemplate
Give the base style an
x:Key
and use it as the base style for an implicitTextBlock
styles inside theControlTemplate
. It's pretty much the same as the top solution, however it's used for base styles that have anx:Key
attribute<Style x:Key="BaseTextBlockStyle" TargetType="{x:Type TextBlock}"> <Setter Property="Foreground" Value="Green" /></Style>...<ControlTemplate.Resources> <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource BaseTextBlockStyle}" /><ControlTemplate.Resources>