Dan Dan - 1 month ago 10
C# Question

WPF Button ControlTemplate won't override Inherited Foreground

My global (

App.xaml
) ControlTemplate for
Button
doesn't want to override the
Foreground
property from its default black colouring. This seems to be a relatively common problem, but I've tried various solutions including setting the
BasedOn
to
null
as described in this question.

My code is below, and you can see I've tried to explicitly state the foreground colour on both the
Grid
and the
ContentPresenter
. Yet the colour stays black. Snoop tells me it's inherited as default, though doesn't seem to say from where, and shows the parent
ContentPresenter
as having
TextElement.Foreground
set to the correct colour.

Is there something in this code that I should be setting? Have I missed an element or property?

<Style TargetType="Button">
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid x:Name="grid" TextBlock.Foreground="#FFD3D3D2">
<Border x:Name="border" Background="Transparent" BorderBrush="#FF5C7999" BorderThickness="2" CornerRadius="{Binding RelativeSource={RelativeSource TemplatedParent},Path=ActualHeight,Converter={StaticResource HalfConverter}}" Padding="10">
<ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10,0" TextBlock.Foreground="#FFD3D3D2">
</ContentPresenter>
</Border>
</Grid>
...

Answer

Testing this, your Style works as you expect if Button.Content is a string, but not if it's a control:

<StackPanel>
    <Button Content="Gray Text As Specified in the ControlTemplate" />
    <Button><Label>Default Black Text</Label></Button>
</StackPanel>

I can add an implicit Label style to ControlTemplate.Resources which overrides the Label's Foreground, but it would be ridiculous to try to have local implicit styles for every possible control somebody could put in there.

But if you just stick with plain strings for the Content, it'll work. Now I'm going to spend some time researching the inheritance rules for attached properties, because I think I'm about 51% semi-confident that this isn't the behavior I'd usually want.

Comments