I was looking at this question and noticed that placing an implicit TextBlock style in Application.Resources applies that style to all TextBlocks, even those inside other controls such as Buttons, ComboBoxes, etc
<Application.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="Blue" />
</Style>
</Application.Resources>
Placing the implicit style in Window.Resources does not cross control template boundaries, so things like Buttons and ComboBoxes maintain their default black text.
<Window.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="Blue" />
</Style>
</Window.Resources>
Furthermore, adding the default style in the Application.Resources makes it so you can’t overwrite that style with another implicit style.
<!-- Doesn't work if implicit style with same property is in Application.Resources -->
<ComboBox.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="Red" />
</Style>
</ComboBox.Resources>
My questions are:
-
Why is this?
-
Are there other differences between
Application.ResourcesandWindows.Resources? -
When should use one over the other?
I understand that
Application.Resourcesapply to the entire application, whileWindow.Resourcesapply to the window only, however I want to know why the styles inApplicationare treated differently than styles inWindow
This is really the only special handling added to WPF and it was done by design. The code that implements it can be found in
FrameworkElement, in the methodFindImplicitStyleResource, which effectively does:So the rule of thumb is that implicit Styles are always applied to controls (i.e. derives from
Control). Assuming the implicit Style can be found.For elements used in a
ControlTemplatethat do not derive fromControl, such asTextBlock, the implicit Style look up will not cross it’s templated parent. In your case above, this would be theComboBox.I believe this was done so that non-application implicit Styles for TextBlock were not inadvertently applied to
TextBlockelements used in control templates, which the developer may or may not have known were there. The implicit Styles would only be applied to TextBlocks actually created by the developer in their own XAML.The application implicit Styles would still allow global styling, such as increasing font size. But has probably caused more confusion than it’s worth.
There is no good answer to say when to use one versus the other, as they each have their function. Obviously if you don’t want to affect every
TextBlockin your application, you shouldn’t put the style in the application resources.But keep in mind that this affects any non-
Controlelement, such asShapeelements.