Friday, July 11, 2008

[Silverlight, C#] Determining Coords with respect to the application

So I am working with multiple user controls, and I have elements in those user controls that I want to drag/drop them seamlessly between without the user knowing about the fact that the elements were being passed back and forth between user controls.

Originally I had been recursively adding together the Top/Left values all the way up to the "root"... however, when I introduced the user controls, it became tricky. Each user control has it's own "root"... so my recursive function would stop at the user control root, and thus my Top/Left values were now only relative to the user control root! Doh!

After digging for awhile, I came across a wonderfully handy little function:
UIElement.TransformToVisual
Returns a transform object that can be used to transform coordinates from the UIElement to the specified object.

With this I made a function that would return me a Point containing the offset X/Y values that would give me the relative coord change needed to move to the new coord space of the wrt element.
/// < summary >
/// Returns the Point that can translate the desired element w.r.t to another element.
/// < /summary >
public static Point getVisualCoordsWRT(UIElement findMe, UIElement wrtMe)
{
  GeneralTransform gt = findMe.TransformToVisual(wrtMe);
  return gt.Transform(new Point(0,0));
}

So to get coords wrt the application I could do this:
Point offset = getVisualCoordsWRT(controlElement, Application.Current.RootVisual);


Thanks to this Silverlight forum post.

.

No comments: