WPF获取相对位置、坐标的方法
1.获取鼠标在控件中的坐标:
1 private void item_MouseDown(object sender, MouseButtonEventArgs e) 2 { 3 Point point = e.GetPosition(lbl); 4 5 } 6 7 //或者直接使用Mouse类的静态方法GetPosition(), 8 //需要注意的是参数为IInputElement类型,也就是说要是能输入的控件 9 Point point2 = Mouse.GetPosition(lbl2); 10 lbl2.Content = "(" + point2.X + ", " + point2.Y + ")";
完整例子代码:
XAML代码
1 <Window x:Class="WpfGetPointDemo.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 Title="MainWindow" Height="350" Width="525"> 5 <Grid x:Name="grid" MouseDown="item_MouseDown"> 6 <Label Background="Red" x:Name="lbl" Margin="293.855,59.398,66.145,77.319"/> 7 <Label Background="GreenYellow" x:Name="lbl2" Margin="29.488,59.398,327.512,69.969"/> 8 <Label Background="blue" x:Name="lbl3" HorizontalAlignment="Left" Margin="133.048,268.187,0,0" VerticalAlignment="Top" Width="250.952" Height="51.813"/> 9 <Button x:Name="btn" HorizontalAlignment="Left" Margin="177.325,10,0,0" VerticalAlignment="Top" Width="135.09" RenderTransformOrigin="0.012,0.547" Height="43.252"/> 10 </Grid> 11 </Window>
后台C#代码
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Windows; 6 using System.Windows.Controls; 7 using System.Windows.Data; 8 using System.Windows.Documents; 9 using System.Windows.Input; 10 using System.Windows.Media; 11 using System.Windows.Media.Imaging; 12 using System.Windows.Navigation; 13 using System.Windows.Shapes; 14 15 namespace WpfGetPointDemo 16 { 17 /// <summary> 18 /// Interaction logic for MainWindow.xaml 19 /// </summary> 20 public partial class MainWindow : Window 21 { 22 public MainWindow() 23 { 24 InitializeComponent(); 25 } 26 27 private void item_MouseDown(object sender, MouseButtonEventArgs e) 28 { 29 Point point = e.GetPosition(lbl); 30 lbl.Content = "("+point.X+", "+point.Y+")"; 31 32 Point point2 = Mouse.GetPosition(lbl2); 33 lbl2.Content = "(" + point2.X + ", " + point2.Y + ")"; 34 35 Point point3 = Mouse.GetPosition(grid); 36 lbl3.Content = "(" + point3.X + ", " + point3.Y + ")"; 37 38 Point point4 = Mouse.GetPosition(btn); 39 btn.Content = "(" + point4.X + ", " + point4.Y + ")"; 40 } 41 } 42 }
运行结果:
2.获取控件相对于两一个控件的坐标:
2.1. 直接使用 control1.TranslatePoint(new Point(), control2)
1 Point point = rectangle.TranslatePoint(new Point(),canvas); 2
2.2.获取控件在Window中的坐标
1 Window window = Window.GetWindow(canvas); 2 Point point = canvas.TransformToAncestor(window).Transform(new Point(0, 0));