Source: WPF methods for acquiring relative positions and coordinates
1. Get the coordinates of the mouse in the control:
1 Private voidItem_mousedown (Objectsender, MouseButtonEventArgs e)2 {3Point point =e.getposition (LBL); 4 5 }6 7 //or directly using the static method of the mouse Class GetPosition (),8 //It is important to note that the parameter is of type IInputElement, that is, if the control can be entered9Point Point2 =mouse.getposition (LBL2);TenLbl2. Content ="("+ Point2. X +", "+ Point2. Y +")";View Code
Complete example code:
XAML Code
1 <Windowx: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= " the"Width= "525">5 <Gridx:name= "Grid"MouseDown= "Item_mousedown">6 <LabelBackground= "Red"x:name= "LBL"Margin= "293.855,59.398,66.145,77.319"/>7 <LabelBackground= "Greenyellow"x:name= "Lbl2"Margin= "29.488,59.398,327.512,69.969"/>8 <LabelBackground= "Blue"x:name= "Lbl3"HorizontalAlignment= "Left"Margin= "133.048,268.187,0,0"VerticalAlignment= "Top"Width= "250.952"Height= "51.813"/>9 <Buttonx:name= "BTN"HorizontalAlignment= "Left"Margin= "177.325,10,0,0"VerticalAlignment= "Top"Width= "135.09"Rendertransformorigin= "0.012,0.547"Height= "43.252"/>Ten </Grid> One </Window>
View Code
Background C # code
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;Ten using System.Windows.Media; One using System.Windows.Media.Imaging; A using System.Windows.Navigation; - using System.Windows.Shapes; - the namespace Wpfgetpointdemo - { -///<Summary> - // Interaction logic for MainWindow.xaml +///</Summary> - Public partial class Mainwindow:window + { A Public MainWindow () at { - InitializeComponent (); - } - - private void Item_mousedown (object sender, MouseButtonEventArgs e) - { in Point point = E.getposition (LBL); - LBL. Content = "(" +point. X+ "," +point. Y+ ")"; to + Point Point2 = Mouse.getposition (LBL2); - lbl2. Content = "(" + Point2. X + "," + Point2. Y + ")"; the * Point Point3 = mouse.getposition (grid); $ Lbl3. Content = "(" + point3. X + "," + Point3. Y + ")";Panax Notoginseng - Point point4 = Mouse.getposition (BTN); the btn. Content = "(" + point4. X + "," + point4. Y + ")"; + } A } the}View Code
Operation Result:
2. Gets the coordinates of a control relative to 21 controls:
2.1. Use Control1 directly. Translatepoint (new Point (), control2)
1 Point point = Rectangle. Translatepoint (new point (), canvas); 2
View Code
2.2. Get the coordinates of the control in window
1 Window window = window.getwindow (canvas); 2 Point point = Canvas. Transformtoancestor (window). Transform (new Point (00));
View Code
Reference: http://www.fengfly.com/plus/view-210427-1.html
How WPF obtains relative positions, coordinates