Ever found yourself with a need to know a controls position in silverlight 2.0, but weren’t using a canvas layout?
You could be implementing a combo box, or a review popup, or a semi-transparent detail panel on a glass pane, and suddenly found that the control you were hoping to trigger this behavior from has no idea where it is. This triggering control, of course, it positioned using a Grid or StackPanel, so it will layout nicely in a variety screen sizes and shapes. Unfortunately, this means it doesn’t have a X or Y position. Does this mean you have to convert your app to use just a Canvas and implement your own layout logic?
The answer is no, you can find the position using UIElement.TransformToVisual() on the Current Application’s RootVisual. The parameter you pass is the control whose location is of interest. This method returns a transform object.
GeneralTransform myButtonTransform = Application.Current.RootVisual.TransformToVisual(myButton);
Now for this to work, the actual object returned by TransformToVisual needs to be of the type MatrixTransform . Typically the RootVisual is a UserControl, and providing another transform hasn’t been applied, it meets this requirement ( as of SL 2.0 Beta2).
if (myButtonTransform is MatrixTransform)
double xPosition = ((MatrixTransform)myButtonTransform).Matrix.OffsetX;
double yPosition = ((MatrixTransform)myButtonTransform).Matrix.OffsetY;
// do stuff with the positions...
The values of xPosition and yPosition have been loaded with are negative values, so we’ll need to make them positive before using them. What follows are the xPosition and yPosition being converted to positive values, each a different way.
double xPosition = Math.Abs(((MatrixTransform)myButtonTransform).Matrix.OffsetX);
double yPosition = -(((MatrixTransform)myButtonTransform).Matrix.OffsetY);
Of course, multiplying by -1 would also work.