Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

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

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...