更改Fill属性时动画矩形颜色

时间:2016-01-11 11:28:01

标签: c# wpf animation

我在WPF中有一个以这种方式定义的矩形;

<Rectangle x:Name="redBrush"   Width="20" Height="20"  Fill="{Binding RectColor}" Stroke="Black" RadiusX="2" RadiusY="2">

我想将颜色的变化从一个变为另一个。

我试过这样的事情:

    <Rectangle x:Name="redBrush"   Width="20" Height="20"  Fill="{Binding NewColor}" Stroke="Black" RadiusX="2" RadiusY="2">
        <Rectangle.Triggers>
            <EventTrigger RoutedEvent="Rectangle.MouseEnter">
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetName="redBrush"
                        Storyboard.TargetProperty="(Rectangle.Fill).Color" To="{Binding NewColor}" Duration="0:0:3" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Rectangle.Triggers>
    </Rectangle>

但我对这种方法有两个问题。我必须使用哪个RoutedEvent?并且ColorAnimation中的To =属性不起作用。

你可以帮帮我吗?感谢

1 个答案:

答案 0 :(得分:0)

故事板是可冻结的对象,您无法使用绑定设置其属性。

解决方法是每次更改Fill DP时生成故事板:

private SolidColorBrush _rectColor;
public SolidColorBrush RectColor {

    get {return _rectColor;}
    set {
        _rectColor = value;
        _sbFillAnimation= CreateFillAnimationStoryboard(_rectColor);
        _sbFillAnimation.Begin();
    }
}

private Storyboard _sbFillAnimation;

private Storyboard CreateFillAnimationStoryboard(SolidColorBrush rectColor) {
    Storyboard sb = new Storyboard() { Duration = TimeSpan.FromSeconds(3), BeginTime = TimeSpan.Zero};

    ColorAnimation colAnim = new ColorAnimation();
    colAnim.From = rectColor.Color;
    colAnim.To = Colors.Gray;
    colAnim.Duration = new Duration(TimeSpan.FromSeconds(3));
    colAnim.AutoReverse = false;

    sb.Children.Add(colAnim);

    Storyboard.SetTarget(colAnim, redBrush);
    Storyboard.SetTargetProperty(colAnim, new PropertyPath("Fill.Color"));


    return sb;
}