Search code examples
windows-phone-7windows-phone-7.1windows-phone-8windows-phonewindows-phone-7.1.1

Get the Absolute Origin of an Object when DragStartedEvent fired


I've an app which like the image shown below (sorry I used an iPhone like mock-ups)

img1

The app has an image as background (displayed using Canvas which takes the whole visual screen size), then another shape (the red rectangle in this case) will shown above the background which can be dragged and pinch zoomed.

Now the question is:

How can I get the coordinates (origins from top-left corner of the screen, i.e. top-left of the canvas) of the top-left corner of the rectangle?


UPDATE

According to @Will's suggestion, I currently move the rectangle in this case via DragDelta using TranslateTransform inside it, like:

rectTransform.X += e.HorizonalChange;
rectTransform.Y += e.VerticalChange;

The rectangle is defined within code, not in XAML:

rect.Stroke = new SolidColorBrush(Colors.Green);
rect.StrokeThickness = 10;
rect.Fill = new SolidColorBrush(Colors.Transparent);
rect.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
rect.VerticalAlignment = System.Windows.VerticalAlignment.Center;
rect.Width = 200;
rect.Height = 200;

canvas.Children.Add(rect);

and the canvas is defined within XAML.


What I've tried:

Initially I was trying to get the start point when the Drag event begins, but by using the DragStarted(object sender, DragStartedGestureEventArgs e), I am only able to output the coords of the point which was touched, but not the point of top-left corner of this rectangle.

And it's similar to the DragCompleted event which will return me the point the gesture ends.

So is there any chance I can get the origin coords of the red rectangle?


Solution

  • I spent nearly an afternoon on Google as well as MSDN and then finally come to find this on SO:

    How to get the position of an element in a StackPanel?

    which enlightened me using the similar method. In that case, they managed to get the absolute coordinates of an UI Element. Similarily, in my case, I intend to know the absolute origin(coordinates) of the red rectangle to the background canvas.

    I use:

    GeneralTransform gt = canvas.TransformToVisual(rect);
    Point currentPos = gt.Transform(new Point(0, 0));
    

    Then the currentPos is the current position of rectangle (its an absolute position, relative to the canvas).

    And Here's the reference of TransformToVisual in MSDN

    There's only one thing to pay attention to: the value of X and Y are negative.