简体   繁体   中英

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

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM