Parham.D
Parham.D

Reputation: 1168

"Specified element is already the logical child of another element. Disconnect it first" error in my code, Any solution?

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?

Upvotes: 3

Views: 10022

Answers (2)

akjoshi
akjoshi

Reputation: 15772

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

Upvotes: 2

sloth
sloth

Reputation: 101052

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

Upvotes: 2

Related Questions