WPF使用TransformToAncestor獲取元素的相對座標

原理:WPF的界面元素是由Visual元素構成的。在可視元素樹Visual中,獲取某個元素相對於它的父級元素(Ancestor)的座標,可以使用TransformToAncestor與Transform方法。

指定中心點,獲取相對座標

例子一:確定TextBlock相對於窗體的位置

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
  <StackPanel Margin="16">
    <StackPanel Margin="8">
      <TextBlock Name="myTextBlock" Margin="4" Text="Hello, world" />
    </StackPanel>
  </StackPanel>
</Window>
// 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的位置

<Window x:Class="測試相對座標與絕對座標.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:測試相對座標與絕對座標"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Canvas Name="myCanvas">
        <Button Width="100"
                    Name="myButton"
                    Click="MyButton_Click"
                    Height=" 100" 
                    Content="我是按鈕"
                    Canvas.Left="100"
                    Canvas.Top="100"/>
    </Canvas>
</Window>
 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;


 獲得子元素相對於父元素位置和寬高

<Canvas x:Name="cv">
        <Rectangle x:Name="rct" Width="100" Height="80" Fill="#FFD62525" Canvas.Left="309" Canvas.Top="181" />
 </Canvas>


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


 
 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章