【问题标题】:How get a current position of textBox如何获取文本框的当前位置
【发布时间】:2012-04-05 12:38:01
【问题描述】:

调用此方法时如何获取文本框元素的当前位置?

 private void UserTextBox_GotFocus(object sender, RoutedEventArgs e)
        {

        }

更新

 GeneralTransform gt = this.TransformToVisual(Application.Current.RootVisual as UIElement);
            Point offset = gt.Transform(new Point(0, 0));
            double controlTop = offset.Y;
            double controlLeft = offset.X;

当我使用这个 controlTop 和 controlLeft 是 (0,0)

【问题讨论】:

    标签: c# silverlight windows-phone-7 silverlight-4.0 silverlight-3.0


    【解决方案1】:

    因为您更新中的“this”是页面对象。在您的 xaml 中使用 x:Name="MyTextbox" 命名您的文本框。然后在您的焦点事件处理程序中:

    private void UserTextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        GeneralTransform gt = MyTextbox.TransformToVisual(Application.Current.RootVisual);
        Point offset = gt.Transform(new Point(0, 0));
        double controlTop = offset.Y;
        double controlLeft = offset.X;
    }
    

    在您的代码中,您试图根据应用程序获取页面的绝对位置,这就是为什么您将偏移值设为 0。

    【讨论】:

      【解决方案2】:

      像这样获取 TextBox 的引用,不要使用“this”。在这种情况下,“this”是一个完全不同的对象:

          private void txt1_GotFocus(object sender, RoutedEventArgs e)
          {
              TextBox t = sender as TextBox;
              GeneralTransform gt ...
          }
      

      【讨论】:

      • 是的,这与我的解决方案相同。唯一的区别是您从事件参数“sender”中获取文本框的引用,但是您不需要这样做,因为您已经使用它的名称从代码隐藏中引用了它。这个想法是,您需要使用对文本框的引用,而不是使用“this”。
      • 如果 TextBox 位于 ListBox 内的 DataTemplate 中,您的解决方案将不起作用。
      • 我明白了,我以为问题中更新后的部分是revolutionkpi添加的部分,而不是你。
      【解决方案3】:

      我希望我的所有文本框都位于右边缘(负 20)。它们都在左侧水平对齐。

      我启用了页面 SizeChanged 事件处理程序,然后添加了:

              private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
              {
                  GeneralTransform gt = tbSvcMsgOut.TransformToVisual(this);
                  Point offset = gt.TransformPoint(new Point(0, 0));
                  double controlTop = offset.Y;
                  double controlLeft = offset.X;
                  double newWidth =  e.NewSize.Width - controlLeft - 20;
                  if (newWidth > tbSvcMsgOut.MinWidth)
                  {
                      tbSvcMsgOut.Width = newWidth;
                      tbDeviceMsgIn.Width = newWidth;
                      tbSvcMsgIn.Width = newWidth;
                      tbDeiceMsgOut.Width = newWidth;
                  }
              }
      

      这对我来说很好用,:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-06
        • 1970-01-01
        • 1970-01-01
        • 2015-07-12
        相关资源
        最近更新 更多