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

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

我试图以编程方式使用 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 但没有任何运气。

您必须将正确的 PropertyPath 指定为 BrushColor

所以不用

PropertyPath colorTargetPath = new PropertyPath(TextBlock.BackgroundProperty);

你必须使用

PropertyPath colorTargetPath =
  new PropertyPath("(0).(1)", TextBlock.BackgroundProperty, SolidColorBrush.ColorProperty);

这相当于您链接答案的 XAML 中的 Storyboard.TargetProperty="(TextBlock.Background).Color"

现在它应该可以工作了 - 至少如果 TextBlock.Background 的现有 BrushSolidColorBrush。如果没有,您必须使 PropertyPath 适应您的 Brush.

类型