Reputation: 554
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
Upvotes: 2
Views: 11778
Reputation: 5655
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);
}
Upvotes: 0
Reputation: 65
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();
}
Upvotes: 2
Reputation: 273179
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.
Upvotes: 10