简体   繁体   English

如何在 WPF 中动态创建矩形?

[英]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.例如,如果 number = 5,程序将生成 5 个矩形。 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#.我正在使用 WPF 和 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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