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

标签 c# wpf xaml button coloranimation

我有一个带有 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>

关于c# - 反复按下按钮时,ColorAnimation 停留在颜色上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17567650/

相关文章:

c# - 如何将属性绑定(bind)到另一个类的属性(没有 UI 控件)?

c# - 合并列表并只返回重复项

c# - 在 WPF DataGrid 的单个单元格上设置删除线的最佳方法?

c# - 绑定(bind)到其他元素(高度减去 5px)

c# - 滚动时弹出窗口不关闭

c# - 在以抽象基类作为参数实现接口(interface)方法时访问派生类属性

C#,WPF,需要时自动调用 Dispatcher.Invoke?

WPF:如何使两个控件( ListView )共享它们之间的整个可用空间?

xaml - System.Type 作为转换器的属性 - 仅适用于代码隐藏中未使用的属性

c# - XamlParseException 是未处理的 C# 应用程序