您当前的位置: 首页 > 

君子居易

暂无认证

  • 0浏览

    0关注

    210博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

WPF使用TransformToAncestor获取元素的相对坐标

君子居易 发布时间:2020-06-05 13:53:11 ,浏览量:0

原理:WPF的界面元素是由Visual元素构成的。在可视元素树Visual中,获取某个元素相对于它的父级元素(Ancestor)的坐标,可以使用TransformToAncestor与Transform方法。

指定中心点,获取相对坐标

例子一:确定TextBlock相对于窗体的位置


  
    
      
    
  
// Return the general transform for the specified visual object.
GeneralTransform generalTransform1 = myTextBlock.TransformToAncestor(this);
 
// Retrieve the point value relative to the parent.
Point currentPoint = generalTransform1.Transform(new Point(0, 0));//窗体位置为(0,0)

 例子二:获取Button的中心点,相对于Canvas的位置


    
        
    
 private void MyButton_Click(object sender, RoutedEventArgs e)
        {
            Point current = new Point();
            current=  this.myButton.TransformToAncestor(this.myCanvas)
.Transform(new Point(myButton.Width/2, myButton.Height/2));//获取中心点的位置
            MessageBox.Show(current.X.ToString() +  "  "+ current.Y.ToString ());
        }

 

获取相对于屏幕的坐标

           

Point controlPoint = new Point(0, 0);
            controlPoint = ((TextBox)sender).PointToScreen(controlPoint);//获取控件相对于屏幕的位置
            mkeyBoard.Top = controlPoint.Y + ((TextBox)sender).ActualHeight;
            mkeyBoard.Left = controlPoint.X-20;

 获得子元素相对于父元素位置和宽高


        
 

后台C#

   private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Rect itemRect = VisualTreeHelper.GetDescendantBounds(rct);//itemRect是0,0,100,80
            Rect itemBounds = rct.TransformToAncestor(cv).TransformBounds(itemRect);// itemBounds是309,181,100,80
            Console.WriteLine(itemRect);
            Console.WriteLine(itemBounds);
        }

   

 

 

 

 

 

关注
打赏
1660814979
查看更多评论
立即登录/注册

微信扫码登录

0.0362s