Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

c# - Canvas.GetTop() returning NaN

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It seems the general consensus is the Canvas.GetTop(x) returns '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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...