Getting the top left coordinates of a WPF UIElement

百般思念 提交于 2020-01-21 06:23:39

问题


I am working on extending the Microsoft resize Adorner example and need to be able to reposition the element after say the bottom left drag handle has been dragged.

So if I have a textbox of say 150 wide, 35 high postitioned on my form, and the bottom left drag handle changes the width to 200 wide, the right hand of the text box remains unchanged but the left hand edge moves to the left.

So I need to know the top left coordinates of the UIElement. I have tried Canvas.GetLeft and Canvas.GetTop but they return NaN which is confusing.

I just tried VisualTreeHelper.GetOffset which does return an offset but when you try and use it in the arrange method of the element it disappears, presumably as the values in the offset are too high.

In the days before Wpf the coordinate system was quite simple, wpf has overcomplicated things I think.


回答1:


And if someone just wants the control's screen coordinates:

Point targetLoc = targetCtrl.PointToScreen(new Point(0, 0));

(this doesn't match the thread's description, but it does match the title. Figured it might help people coming in off search results)




回答2:


You can transform coordinates of the UIElement to its parent. In your case it's a form. Here is an example of a method that returns coordinates of a visual:

private Point GetPosition(Visual element) {
   var positionTransform = element.TransformToAncestor(MyForm);
   var areaPosition = positionTransform.Transform(new Point(0, 0));

   return areaPosition;
}


来源:https://stackoverflow.com/questions/4492734/getting-the-top-left-coordinates-of-a-wpf-uielement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!