Skip to main content
 首页 » 编程设计

c#之反复按下按钮时,ColorAnimation 停留在颜色上

2024年02月13日14lyhabc

我有一个带有 ColorAnimation 的自定义 button-style。

这很好用,但是当反复按下多次时,它会停留在目标颜色上。

<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> 

我该如何解决这个问题?

请您参考如下方法:

更新

是的,如果您负担不起删除Trigger.ExitActions 中的Storyboard,那么您确实必须解决From 问题以进行中间启动Storyboard 是你自己。

然而,指定硬编码的From不是唯一的解决方案。您可以让动画在启动时自行重置为基础颜色。

这样做的好处是,通过不指定 From,您可以减少跟踪 future 更新的事情。

<Storyboard AutoReverse="True"> 
 
  <!-- By not specifying a To or From we pretty much reset the property to un-animated state(Exactly what the hard-coded from does) --> 
  <ColorAnimation Duration="0:0:0" 
                  Storyboard.TargetProperty="(Foreground).(SolidColorBrush.Color)" /> 
 
  <!-- This part is same as original time to kick into new Foreground as desired --> 
  <ColorAnimation Duration="0:0:1.5" 
                  Storyboard.TargetProperty="(Foreground).(SolidColorBrush.Color)" 
                  To="Red" /> 
</Storyboard>