Newbie WPF: Does the animation remove the attached property?

147 views Asked by At

I am trying to learn WPF and animations. I have a simple program that allows the user to move an ellipse by using the mouse. When the mouse button is released, the ellipse's position is animated towards the top of the screen.

This works fine the first time I grab the ellipse. But the second time I grab the ellipse I can not change it's y-position anymore (but I can still change the x-position). Does the animation somehow remove the attached Canvas.Top property? How Can I correct this problem?

Here is the code that starts the animation (located in the MouseUp handler)

Duration duration = new Duration(TimeSpan.FromSeconds(5.0*oldY/1000));

DoubleAnimation anim = new DoubleAnimation(oldY, 0, duration); // move to top of canvas

_shapeSelected.BeginAnimation(Canvas.TopProperty, anim);

and here is the mouse move handler

    private void Canvas_MouseMove_1(object sender, MouseEventArgs e)
    {

        if (_shapeSelected != null)
        {
            Point pt = e.GetPosition(theCanvas);

            Canvas.SetLeft(_shapeSelected, (pt.X-_posOfMouseOnHit.X) + _posOfShapeOnHit.X );
            Canvas.SetTop(_shapeSelected,  (pt.Y-_posOfMouseOnHit.Y) + _posOfShapeOnHit.Y );

        }

    }
2

There are 2 answers

2
Clemens On BEST ANSWER

Set the animation's FillBehavior to Stop. As the property now reverts to its current local value when the animation has finished, you also have to set the local value after the animation has started.

var anim = new DoubleAnimation(oldY, 0, duration, FillBehavior.Stop);

_shapeSelected.BeginAnimation(Canvas.TopProperty, anim);
Canvas.SetTop(_shapeSelected, 0); 
0
Fratyx On

As you can see in here in MSDN, values set by animations (rank 2) have a higher precedence as than the local value (rank 3). If you want to set the value manually again you have to stop or remove the animation before. (See also section 'Coercion, Animations, and Base Value' on this site)