Search code examples
wpfpanelboundsvisualtreehelper

Bounds rectangle of selected controls in wpf


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


Solution

  • 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.