judehall
judehall

Reputation: 943

Rectangles in StackPanel

I'm trying to insert multiple rectangles in a stackpanel but I keep getting the error 'Element is already the child of another element.'. Same thing happens if I use a canvas.

Example:

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

...put some rectangles in 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 insert rectangles dynamically in a horizontal orientation. According to the Internet I should be able to do this (manually at least) but...

What to do, what to do? :)

Upvotes: 3

Views: 1694

Answers (1)

Alex Aza
Alex Aza

Reputation: 78507

Seems like you are adding the same rectangle more than once.

If you need to add different rectangles than the code would be 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.

Upvotes: 1

Related Questions