How can I create Rectangles in WPF dynamically?

Sen picture Sen · Oct 27, 2010 · Viewed 9.3k times · Source

I am trying to create rectangles and the number of rectangles is depend on data passed from database. For example, if number = 5, the program will generate 5 rectangles. Also, these rectangles must be able to follow my rectangle property settings, like height, width,color...put them in one line at the end.

Is there a way to do that?

I am using WPF and C#.

Thank you.

Answer

Butzke picture Butzke · Oct 2, 2013

To create the rectangle in code dynamically:

int number = 5;
int width = 10;
int height = 10;
int top = 20;
int left = 20;

for (int i = 0; i < number; i++)
{
    // Create the rectangle
    Rectangle rec = new Rectangle()
    {
        Width = width,
        Height = height,
        Fill = Brushes.Green,
        Stroke = Brushes.Red,
        StrokeThickness = 2,
    };

    // Add to a canvas for example
    canvas.Children.Add(rec);
    Canvas.SetTop(rec, top);
    Canvas.SetLeft(rec, left);
}