12

I've got a Canvas with a few UIElements on. After I've moved them on the canvas by animating the top and left properties, very occasionally a subsiquent call to Canvas.GetTop results in NaN.

Am I not 'closing' the animations properly?

Here's how I'm doing the move

private void InternalMove(double durationMS, FrameworkElement fElement, Point point, EventHandler callback)
{
   _moveElement = fElement;
   _destination = point;

   Duration duration = new Duration(TimeSpan.FromMilliseconds(durationMS));

   DoubleAnimation moveLeftAnimation = new DoubleAnimation(Canvas.GetLeft(fElement), point.X, duration, FillBehavior.Stop);
   Storyboard.SetTargetProperty(moveLeftAnimation, new PropertyPath("(Canvas.Left)"));

   DoubleAnimation moveTopAnimation = new DoubleAnimation(Canvas.GetTop(fElement), point.Y, duration, FillBehavior.Stop);
   Storyboard.SetTargetProperty(moveTopAnimation, new PropertyPath("(Canvas.Top)"));

   // Create a storyboard to contain the animation.
   _moveStoryboard = new Storyboard();
   if (callback != null) _moveStoryboard.Completed += callback;

   _moveStoryboard.Completed += new EventHandler(s1_Completed);
   _moveStoryboard.Children.Add(moveLeftAnimation);
   _moveStoryboard.Children.Add(moveTopAnimation);
   _moveStoryboard.FillBehavior = FillBehavior.Stop;
   _moveStoryboard.Begin(fElement);
}

private void s1_Completed(object sender, EventArgs e)
{
    if (_moveStoryboard != null)
    {
       _moveStoryboard.BeginAnimation(Canvas.LeftProperty, null, HandoffBehavior.Compose);
       _moveStoryboard.BeginAnimation(Canvas.TopProperty, null, HandoffBehavior.Compose);
    }

    Canvas.SetLeft(_moveElement, _destination.X);
    Canvas.SetTop(_moveElement, _destination.Y);
}

thanks

PaulB
  • 23,264
  • 14
  • 56
  • 75

3 Answers3

20

It seems than Canvas.GetTop(x) can return 'Nan' if the value is not explictly set (even tho I do explicitly set it I still sometimes get that result).

An alternative method I'm now using is

Vector offset = VisualTreeHelper.GetOffset(fElement);

which returns the position of fElement within it's container.

PaulB
  • 23,264
  • 14
  • 56
  • 75
  • Oops accidentally hit the down arrow first ! Now back to what I intended giving a positive tick. – Jim Dec 23 '15 at 00:51
  • Not the "the general consensus" but just the default value of the attached property. – Clemens Feb 20 '23 at 22:30
1

I've run into a similar situation (NaN), but in a different context. As I recall, it had something to do with how the element was positioned in the container.

Sorry I couldn't provide more help, but maybe this will provide some guidance.

CodeMonkey1313
  • 15,717
  • 17
  • 76
  • 109
-1

Check back your xaml file in Properties Layout make sure value of left or top show only number but not mix (auto). Example: Top 123(auto), this caused Canvas.GetTop will return NaN.