用于Brush属性的WPF ColorAnimation

时间:2010-02-12 00:04:10

标签: wpf animation converter coloranimation

我想知道是否有人可以帮助我 - 我有一个标签,当我在后面的代码中调用一个方法时,我需要能够在任何两种颜色之间交叉淡入淡出。

到目前为止我的最佳尝试:

Private OldColor as Color = Colors.White
Sub SetPulseColor(ByVal NewColor As Color)
    Dim F As New Animation.ColorAnimation(OldColor, NewColor, New Duration(TimeSpan.Parse("00:00:01")))
    OldColor = NewColor
    F.AutoReverse = False
    PulseLogo.BeginAnimation(Label.ForegroundProperty, F)

End Sub

我遇到的问题是ColorAnimation返回Media.Color,Foreground的属性类型是Brush。

我知道如何创建合适的画笔,但不知道如何在动画中创建它。

从谷歌搜索,似乎我需要一个转换器:

<ValueConversion(GetType(SolidColorBrush), GetType(SolidColorBrush))> _
Public Class ColorConverter
    Implements IValueConverter

Public Function Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        Dim Color As Color = DirectCast(value, Color)
        Return New SolidColorBrush(Color)
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Return Nothing
    End Function

End Class

但是我见过的所有例子都将它绑定到XAML中的动画 - 我想在后面的代码中执行它...

有人可以指出我正确的方向吗?

由于

2 个答案:

答案 0 :(得分:22)

通常的解决方法是不使用转换器,而是使画笔的颜色设置动画。但是,要做到这一点,你需要一个PropertyPath,这反过来意味着你需要一个故事板:

Storyboard s = new Storyboard();
s.Duration = new Duration(new TimeSpan(0, 0, 1));
s.Children.Add(F);

Storyboard.SetTarget(F, PulseLogo);
Storyboard.SetTargetProperty(F, new PropertyPath("Foreground.Color"));

s.Begin();

(原谅C#语法)

注意SetTargetProperty调用中的属性路径,该路径遍历Foreground属性并进入生成的画笔的Color属性。

您还可以使用此技术为渐变画笔等中的各个渐变色标设置动画

答案 1 :(得分:0)

            ColorAnimation colorChangeAnimation = new ColorAnimation();
            colorChangeAnimation.From = VariableColour;
             colorChangeAnimation.To = BaseColour;
            colorChangeAnimation.Duration = timeSpan;

            PropertyPath colorTargetPath = new PropertyPath("(Panel.Background).(SolidColorBrush.Color)");
            Storyboard CellBackgroundChangeStory = new Storyboard();
            Storyboard.SetTarget(colorChangeAnimation, BackGroundCellGrid);
            Storyboard.SetTargetProperty(colorChangeAnimation, colorTargetPath);
            CellBackgroundChangeStory.Children.Add(colorChangeAnimation);
            CellBackgroundChangeStory.Begin();

// VariableColour&amp; BaseColour是Color类,timeSpan是TimeSpan类,BackGroundCellGrid是Grid类;

//无需在XAML中创建SolidColorBrush并绑定到它; //玩得开心!