Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the top left coordinates of a WPF UIElement

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.

like image 458
user547708 Avatar asked Dec 20 '10 18:12

user547708


2 Answers

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)

like image 129
Bill Tarbell Avatar answered Oct 19 '22 00:10

Bill Tarbell


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;
}
like image 35
Pavlo Glazkov Avatar answered Oct 19 '22 00:10

Pavlo Glazkov