Rectangles in StackPanel

I am trying to insert several rectangles on the stack, but I keep getting an error. An element is already a child of another element. The same thing happens if I use canvas.

Example:

List<Rectangle> recList = new List<Rectangle>();

... put some rectangles on the list

StackPanel stack = new StackPanel();

foreach(var item in recList)
     stack.Children.Add(item); // get error here on 2nd item trying to add

uiStackPanel.Children.Add(stack); // declared in XAML

I want to be able to dynamically insert rectangles in horizontal orientation. According to the internet, I should be able to do this (at least manually), but ...

What to do, what to do? :)

+3
source share
1 answer

It seems you add the same rectangle more than once.

If you need to add different rectangles than the code will look like this:

var list = new List<Rectangle>();
for (int i = 0; i < 10; i++)
{
    list.Add(new Rectangle());
}

var panel = new StackPanel();
foreach (var rectangle in list)
{
    panel.Children.Add(rectangle);
}

This code works.

+1
source

All Articles