Determine the bounding rect of a WPF element relative to some parent
Solution 1
It is quite simple:
public static Rect BoundsRelativeTo(this FrameworkElement element,
Visual relativeTo)
{
return
element.TransformToVisual(relativeTo)
.TransformBounds(LayoutInformation.GetLayoutSlot(element));
}
In fact it may be overkill to put it in a separate method.
Solution 2
The LayoutSlot option didn't work for me at all. This ended up giving me a child position relative to a specified parent/ancestor control:
public static Rect BoundsRelativeTo(this FrameworkElement child, Visual parent)
{
GeneralTransform gt = child.TransformToAncestor(parent);
return gt.TransformBounds(new Rect(0, 0, child.ActualWidth, child.ActualHeight));
}
Solution 3
Taking into account a few suggestions i found here this solved the problem for me.
item.TransformToVisual( relativeToElement )
.TransformBounds( new Rect( item.RenderSize ) );
Solution 4
Nevermind, I finally managed to figure it out using a combination of LayoutInformation.GetLayoutSlot()
(although I probably could have used either ActualWidth
/ActualHeight
or RenderSize
) and UIElement.TranslatePoint()
.
Seems a rather complicated solution when it could be as simple as this:
myElement.GetBounds( relativeElement );
Oh well. Maybe time for an extension method. :)
devios1
I am a coder: an architect of thought. My name is Logan. I am the founder and sole employee of The Little Software Company. My current project is developing a textual layout language to replace Auto Layout and Interface Builder (ambitious huh?). I'm currently working for Quetzal POS on our next-gen iPad based point of sale.
Updated on July 24, 2022Comments
-
devios1 almost 2 years
I consider this a pretty simple request, but I can't seem to find a conclusive answer in my searches. How can I determine the bounds of a particular visual element in my window, relative to some other parent element?
I've tried using
LayoutInformation.GetLayoutSlot
but this just seems to return aRect
at 0,0 and doesn't reflect the actual location of the element.What I'm trying to do is take a "screenshot" of a window using
RenderTargetBitmap
and then crop it to a particular element, but I can't get the element's bounds to know what to crop the bitmap to!