...">

WPF: Get the position of a child UIElement inside its parent. Ignore RenderTransform if any

Suppose I have this XAML code:

<DockPanel Name="pan"> <Label Content="AAA" Name="lab1" /> <Label Content="BBB" Name="lab2" /> <Label Content="CCC" Name="lab3" /> </DockPanel> 

My code is behind me. I want to know what are the coordinates of lab2 inside pan . Hovewer I want to ignore any existing RenderTransform lab2 . Thus, the solution should return the same coordinates for the above code and the following:

 <DockPanel> <Label Content="AAA" /> <Label Content="BBB" > <Label.RenderTransform> <TranslateTransform Y="20"/> </Label.RenderTransform> </Label> <Label Content="CCC" /> </DockPanel> 

In other words, I need a position that was set by the ArrangeOverride pan method when calling Arrange on but2 . I would call this a "logical position." The "visual position" can be obtained by calling the following method:

 private Point visualPoss() { Point lab2Vis = lab2.PointToScreen(new Point(0, 0)); Point panVis = pan.PointToScreen(new Point(0, 0)); return new Point(lab2Vis.X - panVis.X, lab2Vis.Y - panVis.Y); } 

But this is not a solution to my problem, since the return value of this visualPoss() not equal for both of the XAML code examples above.

Please leave a comment if someone is unclear.

thanks

+4
source share
2 answers

There seems to be a very simple and clear solution:

 private Point logicalPoss() { Vector vec = VisualTreeHelper.GetOffset(lab2); return new Point(vec.X, vec.Y); } 

It looks like it is working well. If you know how this works, do not leave a comment.

+6
source

I would get the conversion and convert it to MatrixTransform . You can then use the Inverse property to cancel the rendering transformation. It will look something like this:

 private Point visualPoss() { Point lab2Vis = lab2.PointToScreen(new Point(0, 0)); Point panVis = pan.PointToScreen(new Point(0, 0)); if (lab2.RenderTransform != null) { var matrix = new MatrixTransform(lab2.RenderTransform.Value); lab2Vis = matrix.Inverse.Transform(lab2Vis); } return new Point(lab2Vis.X - panVis.X, lab2Vis.Y - panVis.Y); } 
+3
source

Source: https://habr.com/ru/post/1336472/


All Articles