简体   繁体   中英

How can I create Rectangles in WPF dynamically?

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM