'ColorAnimation'动画对象不能用于为属性'Background'设置动画,因为它是不兼容的类型'System.Windows.Media.Brush'

时间:2016-10-18 15:37:27

标签: c# wpf wpf-animation

我想以编程方式使用ColorAnimation为单元格设置动画,但是当我执行storyboard.Begin()时我得到了这个

'System.Windows.Media.Animation.ColorAnimation' animation object cannot be used to animate property 'Background' because it is of incompatible type 'System.Windows.Media.Brush'.

我已将ColorAnimation定义为

var storyBoard = new  Storyboard();
ColorAnimation colorAnimation = new ColorAnimation
{
    From = Colors.Red,
    To = Colors.CornflowerBlue,
    Duration = TimeSpan.FromSeconds(1),
    FillBehavior = FillBehavior.Stop
};

以及我的用法

if (column.UniqueName != "_ID")
{
    var animation = animationMapping[column.UniqueName].Animation;
    var storyboard = animationMapping[column.UniqueName].Storyboard;

    Storyboard.SetTarget(animation, cell.Content as TextBlock);
    //Storyboard.SetTargetProperty(animation,
    //    new PropertyPath((TextBlock.Foreground).Color"));

    PropertyPath colorTargetPath = new PropertyPath(TextBlock.BackgroundProperty);
    Storyboard.SetTargetProperty(animation, colorTargetPath);

    storyboard.Begin();
}

我必须传递给新的PropertyPath什么参数?我试图跟随this example,但没有任何运气。

1 个答案:

答案 0 :(得分:4)

您必须为PropertyPath的{​​{1}}指定正确的Color

所以而不是

Brush

你必须使用

PropertyPath colorTargetPath = new PropertyPath(TextBlock.BackgroundProperty);

这相当于您链接答案的XAML中的PropertyPath colorTargetPath = new PropertyPath("(0).(1)", TextBlock.BackgroundProperty, SolidColorBrush.ColorProperty);

现在它应该有效 - 至少如果Storyboard.TargetProperty="(TextBlock.Background).Color"的现有BrushTextBlock.Background。如果没有,则必须使SolidColorBrush适应您的PropertyPath类型。