John Sourcer
John Sourcer

Reputation: 451

Relative position with TransformToAncestor

I have a canvas (ZoomableCanvas) which implements zooming and has child items. I'm trying to get the relative position of a child item when zooming in, in order to display extended information over it.

<Canvas x:Name="CanvasContainer" Width="1500" Height="780">
    <ZoomableCanvas ApplyTransform="false" Loaded="ZoomableCanvas_Loaded" x:Name="ShareCanvas" Width="1500" Height="780" MinWidth="1500" MinHeight="780" Grid.Row="0" Grid.Column="0" />
</Canvas>

Code behind:

Canvas main = touched.FindVisualParent<Canvas>(); //Finds "CanvasContainer"
Point relativePoint = touched.TransformToAncestor(main).Transform(new Point(0, 0));
double canvasTop = Canvas.GetTop(touched);

But here canvasTop != relativePoint.Y before zooming?

Am I using this incorrectly. Doesn't it map to the parent visual and give a relative point?

Upvotes: 0

Views: 3100

Answers (1)

Clemens
Clemens

Reputation: 128077

The values you're comparing will only be equal if

  • There is no transform (RenderTranform or LayoutTransform) set on touched, since these are taken into account in TransformToAncestor but not in the Canvas.Left or Canvas.Top properties.

  • The ZoomableCanvas has no offset relative to the outer canvas. This is because Canvas.GetTop(touched) returns the top offset relative to the ZoomableCanvas (assumed that touched is a child of the ZoomableCanvas), whereas relativePoint is relative to the outer Canvas.


To illustrate the first issue, just put an element with a RenderTransform into a Canvas:

<Canvas x:Name="canvas">
    <Label x:Name="child" Content="Hello" Canvas.Left="50" Canvas.Top="100">
        <Label.RenderTransform>
            <TranslateTransform X="50" Y="100"/>
        </Label.RenderTransform>
    </Label>
</Canvas>

If you'd call

var point = child.TransformToAncestor(canvas).Transform(new Point());
var left = Canvas.GetLeft(child);
var top = Canvas.GetTop(child);

it would return point as (100, 200), whereas left is 50 and top is 100.

Upvotes: 1

Related Questions