您现在的位置是:首页 > 文章详情

WPF获取相对位置、坐标的方法

日期:2018-07-06点击:769
原文: 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 + ")";
View Code

完整例子代码:

   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>
View Code

   后台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 }
View Code

   运行结果:

    

2.获取控件相对于两一个控件的坐标:

   2.1. 直接使用  control1.TranslatePoint(new Point(), control2)

1 Point point = rectangle.TranslatePoint(new Point(),canvas); 2 
View Code

  2.2.获取控件在Window中的坐标

1 Window window = Window.GetWindow(canvas); 2 Point point = canvas.TransformToAncestor(window).Transform(new Point(0, 0)); 
View Code

 

引用:http://www.fengfly.com/plus/view-210427-1.html

原文链接:https://yq.aliyun.com/articles/678245
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章