“Element is already the child of another element.”

僤鯓⒐⒋嵵緔 提交于 2019-12-02 05:04:40

问题


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


回答1:


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.




回答2:


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();
}



回答3:


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);
    }


来源:https://stackoverflow.com/questions/10019259/element-is-already-the-child-of-another-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!