wpftemplatestemplatebindingcoloranimation

ColorAnimation with subtractive By property


How to make WPF subtract By property from Template binded background?

I want to animate my background of button's template using "By" property. It works correctly if i need to make background lighter, because "By" adds up with "back color". But actually I want to make it darker, and I don't know how to make WPF subtract By property from Template binded background.

<Border x:Name="BackRect" Background="{TemplateBinding Background}" 
                CornerRadius="15" BorderThickness="0" Height="115" Width="215">
                <ContentControl x:Name="MainTitle"
                            FontFamily="Inter"    
                            FontSize="{TemplateBinding FontSize}" 
                            Content="{TemplateBinding Content}"
                            HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>

<ControlTemplate.Triggers>
            <EventTrigger RoutedEvent="MouseEnter">
                <BeginStoryboard>
                    <Storyboard> 
                        <ColorAnimation Storyboard.TargetName="BackRect" Storyboard.TargetProperty=(Button.Background).(SolidColorBrush.Color)"
                                        By="#A0A0A0" FillBehavior="HoldEnd" Duration="0:0:0.3" >
                            <ColorAnimation.EasingFunction>
                                <SineEase EasingMode="EaseOut"/>
                            </ColorAnimation.EasingFunction>
                        </ColorAnimation>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
</ControlTemplate.Triggers>

Solution

  • It seems that, despite apparently not mentioned in the documentation, you can use negative values for the ScA, ScR, ScG and ScB properties of the Color struct, so that you can get a subtracted Color by means of a ColorAnimation's By property.

    Here is an example:

    <Rectangle Width="300" Height="200">
        <Rectangle.Fill>
            <SolidColorBrush Color="Red"/>
        </Rectangle.Fill>
        <Rectangle.Triggers>
            <EventTrigger RoutedEvent="MouseEnter">
                <BeginStoryboard Name="AnimateFillColor">
                    <Storyboard>
                        <ColorAnimation
                            Storyboard.TargetProperty="Fill.Color"
                            Duration="0:0:0.2">
                            <ColorAnimation.By>
                                <Color ScR="-0.5"/>
                            </ColorAnimation.By>
                        </ColorAnimation>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
            <EventTrigger RoutedEvent="MouseLeave">
                <StopStoryboard BeginStoryboardName="AnimateFillColor"/>
            </EventTrigger>
        </Rectangle.Triggers>
    </Rectangle>