Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change ContentPresenter Color WPF

I have a custom button in WPF. On disabled state I want it's content color to change, but I can't manage to do that. I'm using Blend for Visual Studio. When I go to edit template and choose contentPresente's brush color it says that value is invalid. How can I do that ? I tried to change it in XAML and this is the code I used but there is an error.

<ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="contentPresenter">
    <EasingColorKeyFrame KeyTime="0" Value="Black" />
</ColorAnimationUsingKeyFrames>
like image 231
Dimitri Avatar asked Sep 18 '25 21:09

Dimitri


2 Answers

ContentPresenter by itself does not have any Visual Style's. It's merely a placeholder for the Content of the Control in the Style which it resides in.

To modify the Foreground in your custom Button's Style.ControlTemplate, you could use the attached property TextElement.Foreground on the ContentPresenter with a Trigger for IsEnabled="False"

...
<ControlTemplate.Triggers>
  ...
  <Trigger Property="IsEnabled"
            Value="False">
    <Setter TargetName="contentPresenter"
            Property="TextElement.Foreground"
            Value="Red" />
  </Trigger>
</ControlTemplate.Triggers>
...

You can accordingly do the same via Storyboard's or the VisualStateManager via blend for the same property.

Note:

Very important to understand that by doing this^^ we are assuming the Button using this Style to have its Content as some Text. If your Button.Content is something else like another FrameworkElement(say a ComboBox) You will not see it become "Red".

like image 69
Viv Avatar answered Sep 20 '25 12:09

Viv


Found a "Hacky" way to do this for any element by using ControlTemplate.Resources and TargetType:

<ControlTemplate x:Key="GlyphButton" TargetType="{x:Type Button}">
  <ControlTemplate.Resources>
    <Style TargetType="{x:Type fa:ImageAwesome}">
        <Setter Property="Foreground" Value="Gray"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsMouseOver, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" Value="true">
                <Setter Property="Foreground" Value="#FF048758"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
  </ControlTemplate.Resources>
  <ContentPresenter/>
</ControlTemplate>

Sadly you can't use button's VisualStateManager this way.

like image 26
Dave_cz Avatar answered Sep 20 '25 12:09

Dave_cz