简体   繁体   中英

Binding to X Y coordinates of element on WPF Canvas

I have a Canvas with 2 "dots" drawn on it. See this (simplified) code:

<Canvas> 
    <Ellipse />
    <Ellipse />
    <Canvas.RenderTransform>
        <RotateTransform x:Name="rotateEllipse" />
    </Canvas.RenderTransform>
</Canvas>

As you can see, I want to rotate the canvas using the given RotateTransform.

Next, I want to put a TextBlock near to each Ellipse (a label). However, I don't want to include this TextBlock into the Canvas because it will then rotate also. I want the text to remain horizontal.

Any idea how to solve this in an elegant way?

Something like this, should work for you

<TextBlock RenderTransform="{Binding RelativeSource={RelativeSource AncestorType=Canvas},
                                                      Path=RenderTransform.Inverse}"/>

Assign to text box transformation matrix an inverse of the transformation matrix of the Canvas .

Good question! And I'm going to guess, so please take this answer with a pinch of salt.

I believe you are trying to place text annotations next to ellipses on a rotated canvas, but these annotations need to remain horizontal. Two things you could try:

  • Firstly, given the XY point that you know of each ellipse from Canvas.GetTop/GetLeft, you could find its new rotated XY location by applying the RotateTransform to the ellipse location, using the formula U = M*V, where U is the output point, V is the input point (XY location of ellipse) and M is the Rotation Matrix.

  • Secondly, you could place a second canvas over the first (assuming they are both in a grid, the second canvas is at higher Z-index and is the same size as the underlying canvas). Call it an annotation layer. Your annotations (text labels) can appear at the new transformed locations and unrotated using this approach.

You'd have to do this in code of course, not Xaml, although you might find a binding friendly approach by creating a value converter on the TextBlock that bound to the source RotateTransform/Ellipse and did this operation for you.

Another approach would be to take the .Inverse of the RotateTransform and apply that to the textblocks, however you may still need to translate to get to the new location. Either way I think it demands some experimentation.

Best regards,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM