Search code examples
c#wpfxamlbuttoncoloranimation

ColorAnimation stuck on color when button is pressed repeatedly


I have a custom button-style with a ColorAnimation.

This works fine, but when pressed multiple times repeatedly, it stays stuck on the target color.

<Style TargetType="Button" x:Key="mainButton">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}">
                    <ContentPresenter Content="{TemplateBinding ContentControl.Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsPressed" Value="True">
                        <Trigger.EnterActions>
                            <BeginStoryboard>
                                <Storyboard>
                                    <ColorAnimation 
                                    Duration="0:0:0.10" 
                                    Storyboard.TargetProperty="(Foreground).(SolidColorBrush.Color)" 
                                    To="Red"
                                    AutoReverse="True"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </Trigger.EnterActions>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

How can I resolve this ?


Solution

  • You have not set the From property on your ColorAnimation. So when you press the button in the middle of its animation, the Storyboard takes the current Foreground color value as its From, and this is the color that the animation reverses back to.

    Now when you repeatedly press the button, the From color moves closer and closer to red, giving the impression that the color is stuck on red.


    Update:

    This answer only points out the problem. Refer to Viv's answer for an elegant solution