0

I have UIElements (circles/rectangles) inside a canvas. I want to get X/Y for a UIElement relative to its parent (Canvas). But I am not able to get it.

There are some solutions for this. I tried doing this (Find position of Button/UIElement on screen relative to grid Windows Phone)

var transform = button.TransformToVisual(grid);        
Point absolutePosition = transform.Transform(new Point(0, 0));

But I am getting 0,0 in absolutePosition. I am able to see the circles properly in the map. But I am not sure why I am getting wrong X/Y.

Here is my actual code.

Canvas.SetLeft(shape, Position.X);
Canvas.SetBottom(shape, Position.Y);
canvas.Children.Add(shape);
var transform = shape.TransformToVisual(canvas);        
Point absolutePosition = transform.Transform(new Point(0, 0));

Whatever I pass in transform.Transform I am getting that in output.

Community
  • 1
  • 1
fhnaseer
  • 7,159
  • 16
  • 60
  • 112
  • Are the Canvas attached properties (Top, Left, Bottom, Right) not suitable? They control the X/Y positions of Canvas child elements. – Steven Rands Jan 26 '15 at 12:57
  • Later I used Canvas.GetLeft. They are working fine. I searched on stackoverflow and the only solution I was able to find out was this (transform). So I was wondering why it is not working on my side, – fhnaseer Jan 26 '15 at 18:54
  • Have you tried @Arie's answer? Looking around on SO it seems like `TranslatePoint` is the preferred approach. Just replace the reference to `grid` in his/her example with a reference to your canvas. – Steven Rands Jan 27 '15 at 09:19

1 Answers1

0

The problem is you changed your layout, and at the moment it has yet to be evaluated and measured. "transforms" should be applied only after your layout has been evaluated and measured.

Try using TranslatePoint instead.

Point positionOnGrid = shape.TranslatePoint(new Point(0, 0), grid);

or try calling UpdateLayout after canvas.Children.Add(shape); and before calling TransformToVisual.

Arie
  • 5,251
  • 2
  • 33
  • 54