"指定的元素已经是另一个元素的逻辑子。断开它首先"在我的code错误,任何解决方案?我的、元素、逻辑、解决方案

2023-09-05 04:36:27 作者:荷尔蒙的味道。

我有一个小问题。

这是我的code:

stackPanelShapesContainer = new StackPanel();
InitializeStackPanle();

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

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

在上面code中的9号线,我得到下面的错误 -

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?

推荐答案

我希望错误的原因应该是清楚的,你的意见和其他职位;我假设你想在一个面板中创建的控制present复制到另一个,如果是这种情况,那么你必须首先克隆了控制,然后将其添加到新的面板。

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.

您可以先使用的XamlWriter ,然后通过使用反序列化的XamlReader ,像这 -

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

不过,你可能会发现你要的解决方法,使其工作,因为在使用一定的局限性 XamlWriter.Save (如使用绑定) - 的 XamlWriter.Save 系列化限制

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 -

的XAML串行器preserving绑定

的XamlWriter和绑定序列化