Reputation: 1191
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>
...
Upvotes: 2
Views: 809
Reputation: 37067
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.
Upvotes: 1
Reputation: 1191
Turns out that the buttons using this style were setting their content to things other than text, or explicitly adding a style-less TextBlock
inside, and this was overriding anything set by the Foreground
attributes in the original code.
Ensuring that only text was set as the button contents, or ensuring that the wrappers thereof were styled appropriately, fixed the problem.
It seems that rubber duck debugging works after all.
Upvotes: 1