Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine the bounding rect of a WPF element relative to some parent

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 a Rect 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!

like image 596
devios1 Avatar asked Aug 12 '10 22:08

devios1


2 Answers

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.

like image 97
Ray Burns Avatar answered Oct 19 '22 11:10

Ray Burns


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));
    }
like image 44
DanW Avatar answered Oct 19 '22 10:10

DanW