views:

18

answers:

1

Is there a simple way to find the rectangle (area and location) that would be required to cover a set of control?? VisualTreeHelper.GetDescandentBounds() works fine, but there are no overloaded methods where I can specify the controls that it should consider for finding the bounds rectangle. Any simple solution will be greatly appreciated.

Thanks

+1  A: 

Rect has a Union(Rect) method, which enlarges the current rect to also include the second rectangle. With linq (dont forget to add using System.Linq; to your code file) it's also fairly simple to get a list of rectangles for a list of visuals:

private Rect GetBoundingRect(Visual relativeTo, List<Visual> visuals)
{
    Vector relativeOffset  = new Point() - relativeTo.PointToScreen(new Point());

    List<Rect> rects = visuals
        .Select(v => new Rect(v.PointToScreen(new Point()) + relativeOffset, VisualTreeHelper.GetDescendantBounds(v).Size))
        .ToList();

    Rect result = rects[0];
    for (int i = 1; i < rects.Count; i++)
        result.Union(rects[i]);
    return result;
}       

Edited code: It will now take the position of the individual visuals into account relative to the given visual.

Bubblewrap
It doesn't give the unified rectangle because the Visuals might appear at difference corners of the parent panel and the calculation in this snippet is based on the visual's descendant bound and not with respect to the parent panel.
sudarsanyes
So, if I have 5 buttons (with same size) arranged in different corners of a panel, the method is always returning a rectangle that resembles a single button's size. actually i need it to return a rectangle that can accommodate all the five buttons. any idea on how to achieve this ??
sudarsanyes
Ah, didn't realize the method worked like that, updating my answer..
Bubblewrap
It works!!! Thanks a lot
sudarsanyes