c# - Canvas.GetTop() 返回 NaN

标签 c# wpf

我有一个带有一些 UIElement 的 Canvas 。在我通过设置 top 和 left 属性的动画将它们移动到 Canvas 上之后,偶尔调用 Canvas.GetTop 会导致 NaN。

我没有正确“关闭”动画吗?

我是这样操作的

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);
}

谢谢

最佳答案

似乎普遍的共识是,如果未明确设置该值,则 Canvas.GetTop(x) 返回“Nan”(即使我明确设置了它,有时我仍然会得到该结果)。

我现在使用的另一种方法是

Vector offset = VisualTreeHelper.GetOffset(fElement);

它返回 fElement 在其容器中的位置。

关于c# - Canvas.GetTop() 返回 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/669071/

相关文章:

c# - 在文本 block 文本 WPF 中使用 &

c# - 键盘事件

wpf - 如何强制以 "Run as Administrator"启动我的应用程序?

c# - 将动态生成的图像分配给 ToggleButton.Content

c# - 如何在编译前将变量传递给 Expression Func Projection

c# - 针对 Linux Docker 容器创建长期运行的 .NET Core 服务

c# - Visual Studio 2013 Typescript 集成中断

c# - 无法使用 Roslyn 以编程方式将成员添加到类中

c# - 以 HTML 格式发送电子邮件无效。为什么?

WPF 架构困惑 RE : Routed Commands, 事件和手势