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
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); }