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

梦想与她 提交于 2019-12-01 15:45:19

If element is the child of a Panel (e.g. Grid) you have to remove it from the Panel's Children collection. If it is set as Content of a ContentControl, you'd have to set that Content to null (or anything else that is not element).

Guillaume,

You can try to additionally use RemoveVisualChild method after RemoveLogicalChild:

this.RemoveLogicalChild(element);
this.RemoveVisualChild(element);
PublishFrameworkElement(element, stream);

Hope this helps, Piotr.

I had similar but slightly different issue but got the same error message. I made a workaround by making an inherited class and calling RemoveLogicalChild (since this is a protected method).

 public partial class PopupWindow : Window
{
    public PopupWindow()
    {
        InitializeComponent();
    }

    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);
        this.RemoveLogicalChild(this.Content);    // since protected method
    }
}

It worked for me. I made a simple example you can see here.

http://wpfgrid.blogspot.com/2013/01/wpf-error-specified-element-is-already.html

Old question but I didn't have luck with the other answers, so I made a extension method to remove the item from its parent.

public static class FrameworkElementHelper
{
    public static void RemoveFromParent(this FrameworkElement item)
    {
        if (item != null)
        {
            var parentItemsControl = (ItemsControl)item.Parent;
            if (parentItemsControl != null)
            {
                parentItemsControl.Items.Remove(item as UIElement);
            }
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!