Inconsistent Error: Element is already the child of another element


  • In the code I use to modify my layout for orientation changes, I use the following code:

    Me.grdLayout.Children.Insert(5, Me.vbxCurrentSets)

    As you can see, these two pieces of code move an element (Me.vbxCurrentSets, which is a ViewBox) from a StackPanel (Me.stkShowHideSets) to a Grid (Me.grdLayout) or vice-versa. Sometimes (but not always) I get the following error:

    Element is already the child of another element.

    I know what this error means, it is pretty much self-explanatory. The two things confusing me are:

    1. Why is this so inconsistent?

    2. Why am I getting it at all?

    Sometimes I get the error almost immediately, and other times I could change the orientation (which is when this code gets called) multiple times and not get the error at all. Does this mean that it is not waiting until it is done being removed before I try to add it again? The inconsistency of the error is making it hard for me to determine what I am doing wrong. Can anyone help me? Thanks.

    Nathan Sokalski njsokalski@hotmail.com http://www.nathansokalski.com/

    Thursday, October 30, 2014 10:59 PM


  • OK, I found the cause of the problem, but I'm not sure what the best solution is. The problem is that when switching between Landscape and LandscapeFlipped (WindowsPhone does not seem to have PortraitFlipped) it triggers the OrientationChanged event, even though I want the same layout for both. So what I need to do is, in the OrientationChanged event, determine the previous orientation as well as the new orientation so that I can determine whether the layout needs changed. Is there a way to do this, or do I need to manually keep track of the orientation with a variable or examine the layout when OrientationChanged is called? Thanks.

    Nathan Sokalski njsokalski@hotmail.com http://www.nathansokalski.com/

    Friday, October 31, 2014 12:15 AM