3

I have a little problem.

This is my code:

stackPanelShapesContainer = new StackPanel();
InitializeStackPanle();

var gotFocusStackPanle =(StackPanel) canvas.Children[gotFocusStackPanelIndex];

foreach (UIElement child in gotFocusStackPanle.Children)
{
     UIElement uiElement = child;
     stackPanelShapesContainer.Children.Add(uiElement);
}

In the line 9 of above code, I get following error -

Specified element is already the logical child of another element. Disconnect it first.

How can I fix it? Any solution?

akjoshi
  • 15,374
  • 13
  • 103
  • 121
Parham.D
  • 1,158
  • 2
  • 12
  • 31
  • 2
    Well what are you trying to do? The error seems reasonably clear... – Jon Skeet Jun 14 '12 at 07:33
  • 1
    What are you trying to do? You are trying to add the children of the canvas to an unrelated stackpanel. Obviously you can't do that, as the message says. – Panagiotis Kanavos Jun 14 '12 at 07:33
  • 1
    it's hard to say, what is **really** going on here, but `uiElement` is already a child of another UI element. in `WPF` you can not any `UIElement` being a child of more then one element. – Tigran Jun 14 '12 at 07:33

2 Answers2

2

uiElement is already the child of gotFocusStackPanle, so you can't add it to stackPanelShapesContainer.

That's what the error message says.

Remove the uiElement from gotFocusStackPanle first.

foreach (UIElement child in gotFocusStackPanle.Children.ToList())
{
     UIElement uiElement = child;
     gotFocusStackPanle.Remove(uiElement)
     stackPanelShapesContainer.Children.Add(uiElement);
}
sloth
  • 99,095
  • 21
  • 171
  • 219
2

I hope the reason for error will be clear to you from comments and other posts; I assume that you want to create a copy of control present in one panel into another, if this is the case then you will have to first clone the control and then add it to new panel.

You can clone a control by first serializing it using XamlWriter and then create a new control by deserializing it using XamlReader, something like this -

foreach (UIElement child in gotFocusStackPanle.Children)  
{  
     string childXaml = XamlWriter.Save(child);

    //Load it into a new object:
    StringReader stringReader = new StringReader(childXaml);
    XmlReader xmlReader = XmlReader.Create(stringReader);
    UIElement clonedChild = (UIElement)XamlReader.Load(xmlReader);

    stackPanelShapesContainer.Children.Add(clonedChild);  
}  

But, you may find yourself applying workarounds to make it work as there are some limitations in using XamlWriter.Save (like with bindings) - Serialization Limitations of XamlWriter.Save

Here are some other approaches for serialization -

An XAML Serializer Preserving Bindings

XamlWriter and Bindings Serialization

Community
  • 1
  • 1
akjoshi
  • 15,374
  • 13
  • 103
  • 121