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

*爱你&永不变心* 提交于 2019-12-11 07:37:01

问题


I'm tring to use a ColorAnimation programmatically to animate a cell, but I got this when I perform 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'.

I've defined my ColorAnimation as

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

and on it's usage I do

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();
}

What paramater do I have to pass to the new PropertyPath? I've tried to follow this example but without any luck.


回答1:


You have to specify the correct PropertyPath to the Color of the Brush.

So instead of

PropertyPath colorTargetPath = new PropertyPath(TextBlock.BackgroundProperty);

you have to use

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

This is the equivalent of Storyboard.TargetProperty="(TextBlock.Background).Color" in the XAML of your linked answer.

Now it should work - at least if the existing Brush of the TextBlock.Background is a SolidColorBrush. If not, you have to adapt the PropertyPath to your type of Brush.



来源:https://stackoverflow.com/questions/40112491/coloranimation-animation-object-cannot-be-used-to-animate-property-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!