WPF Canvas.GetLeft()始终接收NaN值

时间:2013-12-27 03:23:43

标签: c# wpf

我正试图在WPF中获取控件的左侧。但我总是收到NaN值而不是双倍值。这是我正在尝试的:

XAML:

<Canvas Canvas.Left="230" Name="cnvSaver">
   <Border Focusable="False"  BorderBrush="#7FBFA379" BorderThickness="0 1" Width="460" Height="460">
       <Canvas Background="#3FFFFFFF" AllowDrop="True" Name="cnvViewerLower" Drop="cnvViewerLower_Drop" Height="460" Width="460">

       </Canvas>
   </Border>
   <Border Focusable="False" Name="borUpper" BorderBrush="#7FBFA379" BorderThickness="1 0">
       <Border.RenderTransform>
            <TranslateTransform x:Name="borUpperTranslate" X="0"/>
       </Border.RenderTransform>
       <Border.Triggers>
            <EventTrigger RoutedEvent="RadioButton.Checked">
                  <BeginStoryboard>
                       <Storyboard Name="stbUpperTranslate" Storyboard.TargetName="borUpperTranslate" Storyboard.TargetProperty="X">
                            <DoubleAnimation RepeatBehavior="Forever" Name="dbaUpperTranslate" From="230" To="0" Duration="0:0:3" AutoReverse="True"/>
                       </Storyboard>
                  </BeginStoryboard>
             </EventTrigger>
         </Border.Triggers>
         <Canvas Background="#3FEEDBB3" Drop="cnvViewerUpper_Drop" MouseLeftButtonDown="cnvViewerUpper_MouseLeftButtonDown" MouseMove="cnvViewerUpper_MouseMove" MouseLeftButtonUp="cnvViewerUpper_MouseLeftButtonUp" AllowDrop="True" Width="460" Height="460" Name="cnvViewerUpper"></Canvas>
      </Border>
</Canvas>

C#背后的代码:

Point p = e.GetPosition(cnvSaver);
            if (x > p.X)
            {
                // Move to Left
                Border br = cnvViewerUpper.Parent as Border;
                double left = Canvas.GetLeft(br) - Math.Abs(p.X - x);
                if(left > 0){
                    Canvas.SetLeft(br, left);
                }
                MessageBox.Show("move to left");
            }
            else if (x == p.X)
            {
                MessageBox.Show("standing");
            }
            else {
                // Move to Right
                double left = Canvas.GetLeft(borUpper);
                if (left > 0)
                {
                    Canvas.SetLeft(borUpper, left);
                }
                MessageBox.Show("move to right");
            }

提前致谢。

1 个答案:

答案 0 :(得分:7)

当您最初明确设置元素时,您只能为Canvas.GetLeft获取值,否则它将返回NaN(这是预期的WPF行为)。

Height and Width

在您的情况下,在您的xaml中,您尚未在Canvas.Left上设置任何border属性,因此当您在代码中访问该属性时,它将返回NaN }。

要获取实际的left坐标,请使用TranslatePoint

p = localItem.TranslatePoint(new Point(0, 0), br);
double currentLeft = p.X;
double currentTop = p.Y;