here is the error I have when I want to attach a FrameworkElement to a new Window to publish it to a PNG file.
So my idea is to remove the parent-child link, call my method, and add the child again with this code :
this.RemoveLogicalChild(element);
PublishFrameworkElement(element, stream);
this.AddLogicalChild(element);
But I got the exact same error...
I looked a lot of questions about this error, here on SO, but none answered to my problem What am I missing ?
EDIT : here is the code that worked for me :
var element = _GeneratedContent as FrameworkElement;
var ParentPanelCollection = (element.Parent as Panel).Children as UIElementCollection;
ParentPanelCollection.Clear();
FileStream stream = [...]
if (element != null)
{
PublishFrameworkElement(element, stream);
ParentPanelCollection.Add(element);
}
stream.Close();
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.
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).
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
Guillaume,
You can try to additionally use RemoveVisualChild method after RemoveLogicalChild:
Hope this helps, Piotr.
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 asContent
of aContentControl
, you'd have to set that Content to null (or anything else that is notelement
).