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?
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
XamlWriterand then create a new control by deserializing it usingXamlReader, something like this –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.SaveHere are some other approaches for serialization –
An XAML Serializer Preserving Bindings
XamlWriter and Bindings Serialization