oliver
oliver

Reputation: 2901

Canvas size as a bounding box of the contained elements

I am implementing a user control that is a view for an arrangement of shapes, which can be moved around and zoomed with the mouse, altogether or individually. The user control contains a single "Root" canvas to which the shapes are added, and the render transform of which determines its position and size in the view.

What I would like to be able is to set the background of the canvas to a rectangle that encloses all its contained shapes. Is this possible ? Of course I can set the Width and Height properties but they seem to count from the origin only. But the shapes can as well be placed at negative coordinates relative to the canvas' origin so the background rectangle of the canvas would have to start at negative coordinates also.

Canvas cnv = new Canvas();
// show the canvas' dimensions
cnv.Background = Brushes.AliceBlue;

for (int i = -5; i < 5; i++)
{
    for (int j = -5; j < 5; j++)
    {
        Rectangle newRectangle = new Rectangle();
        cnv.Children.Add(newRectangle);
        newRectangle.Width = 7;
        newRectangle.Height = 7;
        newRectangle.Fill = Brushes.Green;
        Canvas.SetTop(newRectangle, j * 10);
        Canvas.SetLeft(newRectangle, i * 10);
    }
}

// these are the right bounding dimensions, but with the wrong origin
cnv.Width = 107;
cnv.Height = 107;

// nothing available like that?
// cnv.Left = -50;
// cnv.Top= -50;

Of course, if everything fails, I could just add another rectangle for the bounds.

Upvotes: 3

Views: 322

Answers (1)

Emond
Emond

Reputation: 50712

The Canvas is transparent so why not stack it on top of a rectangle in a grid:

<Grid>
    <Rectangle Fill="Lime" Stroke="Red" StrokeThickness="5" />
    <Canvas />
</Grid>

Or if it realy has to look like a border:

<Border Background="Lime" BorderBrush="Red" BorderThickness="5">
    <Canvas />
</Border>

Upvotes: 1

Related Questions