wpfmvvmfillcoloranimation

Problems implementing ColorAnimation in Ellipse Fill


I am attempting to implement a ColorAnimation on the Fill of an Ellipse, but not having any success. (I am implementing this ColorAnimation in the code-behind of my app's MainWindow, called via the Messenger pattern from the View Model.):

public partial class MainWindow : Window
{
    private SolidColorBrush fillBrush = new SolidColorBrush(Colors.Red);
    private ColorAnimation ca = new ColorAnimation(Colors.Red, Colors.Yellow, new Duration(TimeSpan.FromMilliseconds(800)));
    private Storyboard flashEllipse = new Storyboard();


    public MainWindow(MainWindowVM viewModel)
    {
        DataContext = viewModel;
        InitializeComponent();

        Messenger.Default.Register<string>(this, StartFlashEllipse, Constants.StartMsg);
        Messenger.Default.Register<string>(this, StopFlashEllipse, Constants.StopMsg);

        RegisterName("EllipseFillBrush", fillBrush);
        Storyboard.SetTargetName(ca, "EllipseFillBrush");
        Storyboard.SetTargetProperty(ca, new PropertyPath("(0).(1)", Ellipse.FillProperty, SolidColorBrush.ColorProperty));
        flashEllipse.Children.Add(ca);
        flashEllipse.RepeatBehavior = RepeatBehavior.Forever;
    }


    private void StartFlashEllipse(string ellipseTag)
    {
        Dispatcher.Invoke(DispatcherPriority.Render, (Action)delegate ()
        {
            Ellipse ellipseToFlash = <code to find Ellipse in Window>;

            ellipseToFlash.Fill = new SolidColorBrush(Colors.Blue);
            flashEllipse.Begin(ellipseToFlash);
        });
    }

    ...
}

I got the PropertyPath code from this StackOverflow question, but I am still getting a similar Exception on the flashEllipse.Begin() line as the OP of this question:

''Fill' property does not point to a DependencyObject in path '(0).(1)'.'

What am I missing here?


Solution

  • You do not need a Storyboard and a complex PropertyPath.

    Just directly start an animation of the Color property of the SolidColorBrush:

    ellipseToFlash.Fill = new SolidColorBrush(Colors.Blue);
    
    ellipseToFlash.Fill.BeginAnimation(SolidColorBrush.ColorProperty, ca);