Search code examples
c#wpfxamltextblockcontentpresenter

Changing the Foreground colour of a ContentPresenter containing a ContentTemplate and TextBlock


I have the following code, it is a button with a geometric icon

<Button Style="{StaticResource Button}" IsEnabled="False">
    <DockPanel>
        <ContentControl Template="{StaticResource geometryMenuContentTemplate}"
                        DataContext="{StaticResource keyboardButtonGeometry}"
                        Style="{StaticResource TopBarIcon}" />
        <TextBlock Style="{StaticResource TopBarHeaderText}" Text="KEYBOARD"/>
    </DockPanel>
</Button>

<ControlTemplate x:Key="geometryMenuContentTemplate" TargetType="ContentControl">
    <Canvas>
        <Path Width="25" Height="25" Stretch="Fill" Fill="{TemplateBinding Foreground}" Data="{Binding}"/>
    </Canvas>
</ControlTemplate>

<StreamGeometry x:Key="keyboardButtonGeometry">
    F1 M 15.8333,2...
</StreamGeometry>

Styled with:

<Style x:Key="Button" TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
    <Setter Property="Foreground" Value="{StaticResource StandardForegroundColor}" />
    <Setter Property="Template" Value="{StaticResource ButtonTemplate}" />
</Style>

<ControlTemplate x:Key="ButtonTemplate" TargetType="Button">
    <Border BorderThickness="{TemplateBinding BorderThickness}"
            BorderBrush="{TemplateBinding BorderBrush}"
            Padding="{TemplateBinding Padding}"
            Background="{TemplateBinding Background}">
        <ContentPresenter Name="ButtonContentPresenter" Margin="{TemplateBinding Padding}" TextBlock.Foreground="Red"/>
    </Border>
</ControlTemplate>


<Style x:Key="TopBarHeaderText" TargetType="TextBlock" BasedOn="{StaticResource StatsHeaderText}">
    <Setter Property="Foreground" Value="White" />
</Style>

The visual output of my code is the following:

Button aspect

I'd like to change (in ButtonTemplate) the foreground color of the Textblock inside the ContentPresenter called ButtonContentPresenter to red color. My code changed the color only of the icon and not the TextBlock. Why? How to change only the Textblock color?

I'd like to get something like this:

Final image


Solution

  • Reading through your code, I noticed that your TextBlock has a style named TopBarHeaderText, But I don't see that style in your question. The reason the image is changing color is because you have it set as the Fill being {TemplateBinding Foreground} - maybe put that setting in the style for the TextBlock (the TopBarHeaderText style)?

    It just looks like (from the code I am seeing) that you may have accidentally flipped the color definitions in the geometryMenuContentTemplate and TopBarHeaderText.