4

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.

Community
  • 1
  • 1
advapi
  • 3,661
  • 4
  • 38
  • 73
  • Use this `PropertyPath colorTargetPath = new PropertyPath("(TextBlock.Background).(SolidColorBrush.Color)", null);` . – AnjumSKhan Oct 18 '16 at 16:21
  • @AnjumSKhan Have you actually tried your code? If I run your code I get an `InvalidOperationException` with the message `Cannot resolve all property references in the property path '(TextBlock.Background).(SolidColorBrush.Color)‌'. Verify that applicable objects support the properties.`. So obviously this code doesn't work. (See my answer for the working one.) – haindl Oct 18 '16 at 17:10

1 Answers1

7

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.

haindl
  • 3,111
  • 2
  • 25
  • 31
  • @haindl I've tried your suggestion but I got 'Background' property does not point to a DependencyObject in path '(0).(1)'. – advapi Oct 19 '16 at 06:56
  • 1
    @advapi You get this error message if the `Background` of the affected `TextBlock` is `null`. (`null` is the default value of a `TextBlock.Background`.) Please check if the `Background` is set to a `SolidColorBrush` before you begin the `Storyboard` because you can't animate something that isn't there. – haindl Oct 19 '16 at 07:51