Infosys Microsoft Alliance and Solutions blog

« Handling AppDomain's AssemblyLoad Event | Main | ASP.NET 2.0 - Fix Summary »

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.

 

TrackBack

TrackBack URL for this entry:
http://www.infosysblogs.com/microsoft-mt/mt-tb.fcgi/116

Comments

Can you explain how can I achieve the same functionality in .Net 1.0 Or 1.1 ?

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.

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?

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);

Thanks Prasad for sharing your findings

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)