WPF - Finding Control Location
Recently for a sample application I was building in WPF, I had to find the location of a button control on the window. Playing around with Button.Margin didn't help much since it gave the position with reference to the immediate parent. So if the button was inside a Grid and the grid itself inside say a StackPanel, the values were incorrect.
Searching on the forums, I got some ideas and following is what worked for me
GeneralTransform transform = button1.TransformToAncestor(this);
Point rootPoint = transform.Transform(new Point(0, 0));
button1 is the control for whom I wanted to find the location. The this represents the top level window. The value obtained in rootPoint is the Left and Top cordinates of the button with respect to the top level window. Adding button's height and width will give the complete location details.

Comments
Can you explain how can I achieve the same functionality in .Net 1.0 Or 1.1 ?
Posted by: Ayan Mitra | November 23, 2007 09:12 AM
Ayan, for .net controls in Winform applications, you can usually do a Control.Location to get the cordinates of the control wrt to its immediate parent. If you want it wrt to its top level parent form, somethign like the following should work
Control.FindForm().PointToClient(Control.Parent.PointToScreen(Control.Location))
The conversion of control's coordinates to screen coordinates should be done wrt to its parent, otherwise there will be a difference equal to the border of the Form.
Posted by: Atul Gupta | November 26, 2007 03:15 AM
I used GeneralTransformation in wpf it works fine with stack panel and grid but as soon as Put my control in tab control (on tab pages it gives error :---
"The specified Visual is not an ancestor of this Visual."
So with tab control how to remove this error or is there any other way in WPF?
Posted by: Prasad | May 6, 2008 06:24 AM
I got the solution for WPF,
Use following to get location of control :--
// Return the offset vector for the TextBlock object.
Vector vector = VisualTreeHelper.GetOffset(myTextBlock);
// Convert the vector to a point value.
Point currentPoint = new Point(vector.X, vector.Y);
Posted by: Prasad | May 6, 2008 06:33 AM
Thanks Prasad for sharing your findings
Posted by: Atul Gupta | May 8, 2008 02:04 AM