如何为GradientStop颜色设置动画?

时间:2017-06-04 16:54:22

标签: c# wpf visual-studio wpf-animation

我在下面尝试了代码,但是在“Storyboard.SetTargetProperty(ca1,new PropertyPath(”GradientStop.ColorProperty“))中出现了一些错误;

sb.Begin(this)抛出InvalidOperationException,无法解析“gradStop1.ColorProperty”。

如何正确设置GradientStop颜色的动画效果?

private void UserControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        LinearGradientBrush lgb = new LinearGradientBrush(
           (Color)ColorConverter.ConvertFromString("#FF1E2838"),
           (Color)ColorConverter.ConvertFromString("#FF2B364F"),
           new Point(0.5, 0),
           new Point(0.5, 1));
        UCBody.Background = lgb;

        ColorAnimation ca1 = new ColorAnimation(
            (Color)ColorConverter.ConvertFromString("#FF1E2838"),
            (Color)ColorConverter.ConvertFromString("#FF1E1E1E"),
            TimeSpan.FromMilliseconds(600));

        ColorAnimation ca2 = new ColorAnimation(
            (Color)ColorConverter.ConvertFromString("#FF2B364F"),
            (Color)ColorConverter.ConvertFromString("#FF2B2B38"),
            TimeSpan.FromMilliseconds(600));

        Storyboard sb = new Storyboard();
        sb.Children.Add(ca1);
        sb.Children.Add(ca2);
        Storyboard.SetTargetName(ca1, "gradStop1");
        Storyboard.SetTargetProperty(ca1, new PropertyPath("GradientStop.ColorProperty"));
        Storyboard.SetTargetName(ca2, "gradStop2");
        Storyboard.SetTargetProperty(ca2, new PropertyPath("GradientStop.ColorProperty"));

        sb.Begin(this);
    }
}

1 个答案:

答案 0 :(得分:0)

您没有名为" gradStop1"的对象或" gradStop2"但您可以使用LinearGradientBrush方法为BeginAnimation的渐变停止设置动画:

private void UserControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    LinearGradientBrush lgb = new LinearGradientBrush(
       (Color)ColorConverter.ConvertFromString("#FF1E2838"),
       (Color)ColorConverter.ConvertFromString("#FF2B364F"),
       new Point(0.5, 0),
       new Point(0.5, 1));
    UCBody.Background = lgb;

    ColorAnimation ca1 = new ColorAnimation(
        (Color)ColorConverter.ConvertFromString("#FF1E2838"),
        (Color)ColorConverter.ConvertFromString("#FF1E1E1E"),
        TimeSpan.FromMilliseconds(600));

    ColorAnimation ca2 = new ColorAnimation(
        (Color)ColorConverter.ConvertFromString("#FF2B364F"),
        (Color)ColorConverter.ConvertFromString("#FF2B2B38"),
        TimeSpan.FromMilliseconds(600));

    lgb.GradientStops[0].BeginAnimation(GradientStop.ColorProperty, ca1);
    lgb.GradientStops[1].BeginAnimation(GradientStop.ColorProperty, ca2);
}