WPF获取相对位置、坐标的方法
1.获取鼠标在控件中的坐标:
private void item_MouseDown(object sender, MouseButtonEventArgs e)
{
Point point = e.GetPosition(lbl);
}
//或者直接使用Mouse类的静态方法GetPosition(),
//需要注意的是参数为IInputElement类型,也就是说要是能输入的控件
Point point2 = Mouse.GetPosition(lbl2);
lbl2.Content = "(" + point2.X + ", " + point2.Y + ")";
完整例子代码
<Window x:Class="WpfGetPointDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid x:Name="grid" MouseDown="item_MouseDown">
<Label Background="Red" x:Name="lbl" Margin="293.855,59.398,66.145,77.319"/>
<Label Background="GreenYellow" x:Name="lbl2" Margin="29.488,59.398,327.512,69.969"/>
<Label Background="blue" x:Name="lbl3" HorizontalAlignment="Left" Margin="133.048,268.187,0,0" VerticalAlignment="Top" Width="250.952" Height="51.813"/>
<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"/>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfGetPointDemo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void item_MouseDown(object sender, MouseButtonEventArgs e)
{
Point point = e.GetPosition(lbl);
lbl.Content = "("+point.X+", "+point.Y+")";
Point point2 = Mouse.GetPosition(lbl2);
lbl2.Content = "(" + point2.X + ", " + point2.Y + ")";
Point point3 = Mouse.GetPosition(grid);
lbl3.Content = "(" + point3.X + ", " + point3.Y + ")";
Point point4 = Mouse.GetPosition(btn);
btn.Content = "(" + point4.X + ", " + point4.Y + ")";
}
}
}
运行结果
2.获取控件相对于两一个控件的坐标:
2.1. 直接使用 control1.TranslatePoint(new Point(), control2)
Point point = rectangle.TranslatePoint(new Point(),canvas);
2.2.获取控件在Window中的坐标
Window window = Window.GetWindow(canvas);
Point point = canvas.TransformToAncestor(window).Transform(new Point(0, 0));
引用地址 http://www.fengfly.com/plus/view-210427-1.html
One comment
看的我热血沸腾啊https://www.237fa.com/