Splinti Splinti - 1 month ago 16
C# Question

default textblock styling

I have the following checkbox

<CheckBox x:Name="checkBox" Content="CheckBox" Width="74"/>


and I have a button

<Button Name="TestButton" Content="Test" />


I want to set a "default" color for the textblock. I achieve that by having a resourcedictionary which has the following content:

<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="White"/>
</Style>


The problem is, that the Button should still have a black Textblock foreground, but although in another sourcedictionary i have the following, it still changes to white:

<Style TargetType="Button">
<Style.Setters>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border BorderThickness="1,0,0,1" CornerRadius="5" Background="{TemplateBinding Background}">
<ContentPresenter
x:Name="ContentPresenter"
Margin="1"
VerticalAlignment="Center"
HorizontalAlignment="Center"
TextBlock.Foreground="Black"
Opacity="1.0"/>
</Border>
</ControlTemplate/>
<Setter.Value/>
</Setter>
</Style.Setters>
</Style


Edit:
The ResourceDictionaries are defined in Application.xaml like this:

<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="TextBlock.xaml"/>
<ResourceDictionary Source="Buttons.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>

Answer

You could try overriding the default TextBlock style locally for the ContentPresenter by defining another one in its Resources:

<ContentPresenter ... >
    <ContentPresenter.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="Foreground" Value="Black" />
        </Style>
    </ContentPresenter.Resources>
</ContentPresenter>

But a better way to set a default control text color is like this in App.Resources. TextElement.Foreground will override this on any given individual element.

<SolidColorBrush 
    x:Key="{x:Static SystemColors.ControlTextBrushKey}" 
    Color="White"
    />

If you use that and discard your default TextBlock style, your original ContentPresenter should work as you had it.