Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create Rectangles in WPF dynamically?

Tags:

c#

wpf

rectangles

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.

like image 803
Sen Avatar asked Oct 27 '10 21:10

Sen


1 Answers

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);
}
like image 57
Butzke Avatar answered Sep 24 '22 19:09

Butzke