"Element is already the child of another element."

Go To StackoverFlow.com

1

At first, this exception doesn't really make sense to me. Why shouldn't i be able to duplicate this object multiple times? but thats not the point:

i use a List. Whenever i navigate to a site, it should do this:

 (App.Current as App).recent.ForEach(x => container.Children.Add(x));

(container = another StackPanel)

the first time, it works. afterwards, i get the exception displayed in the questiontitle. i already tried using a listbox, but i just got a ArgumentException. I think these exceptions have the same source, but i don't know what i'm doing wrong. please help

thanks

2012-04-04 21:08
by roqstr


10

The error is quite clear: A WPF/SL Control can only belong to 1 Parent control at a time.

So you'll either have to remove the Controls from their Parent when you are moving away from a Page or you'll have to Create (possibly Clone) new Controls in this ForEach.

2012-04-04 21:18
by Henk Holterman
isn't the page created completely new when navigating to it? i'll try to copy the list - roqstr 2012-04-04 21:35
The target page is created but the old one is not immediately destroyed. Your exception is prove of that - Henk Holterman 2012-04-04 21:37
embarrasing, but i dont get it i try to clone the list like that: List cache = new List ((App.Current as App).recent); but i still get this exceptio - roqstr 2012-04-04 22:00
That clones the List (of references). Unfortunately you will have to clone or remove each individual control - Henk Holterman 2012-04-04 22:05
List cacheList = new List(); (App.Current as App).recent.ForEach(x => cacheList.Add(x)); cacheList.ForEach(x=> container.Children.Add(x)); not working to - roqstr 2012-04-04 22:10
You're still only copying references, not instances. You'll need a new SomeControl() in there somehow - Henk Holterman 2012-04-04 22:57


1

When you navigate to a page, the old instance is not removed instantly, so when you add your controls to the new page, they may still be used in the old page if it's not destroyed, causing the exception.

Try overriding the OnNavigatedFrom(NavigationEventArgs e) and OnNavigatingFrom(NavigatingCancelEventArgs e) methods that are invoked when you leave a page so that you empty your StackPanel.

For example, you could do :

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    base.OnNavigatedFrom(e);
    container.Children.Clear();
}
2013-09-03 07:16
by Mr__Mitch


0

You have to remove the container's children when you navigate from the page. But not if the navigation is due to a suspend. To avoid the children clear when the navigation is due to a suspend it is better to override OnNavigatingFrom instead of OnNavigatedFrom

protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        container.Children.Clear();
        base.OnNavigatingFrom(e);
    }
2015-04-01 19:08
by Pierre Poliakoff
Ads