Facebook Twitter Gplus LinkedIn RSS
formats

Element is already the child of another element – Arghhhhhh

Sometimes I just hate Silverlight. Spent 5 hours debugging a problem that resulted in the “Element is already the child of another element” InvalidOperation exception. I looked at everything; looked to see if I was accidentally reparenting something: no. Looked for unexpected recursion: no. Played with every debugger setting to get more information and finally disected the application – all to no avail.

Then I noticed I’d commented out an Image in one of my templates (derived from a Telerik template for tree nodes) and happened to notice that it was the target of a Storyboard. Yep that was it – not an error that reads “You’ve targeted an element that doesn’t exist” oh no. “Element is already the child of another element” – like hell it was :)

So word to the wise, if you don’t think you are actually making an element the child of another element, look for any inconsistencies in your storyboards and animations.

Help is at hand:

Since writing this post I’ve come up with an algorithm to help identify XAML markup that causes this exception. The post here has a link to the project and a description of the approach.

5 Responses

  1. I agree with Giacomo. I just encountered this problem. I am binding ControlA.Prop1 to ControlB.Prop1 via ElementName binding. Turns out that ControlA.Prop1 was not a DependencyProperty and needed to be changed in order to support binding. The error message was not intuitive, obviously, but I’m glad this post was able to help.

  2. Giacomo

    This error seems to be a catch-all. I was getting this because I typo’d in my custom Panel’s MeasureOverride. The typo caused an ArgumentOutOfRangeException to be thrown, which apparently causes Silverlight to freak out and throw this generic error.

    • Yes, I do seem to keep getting it for general XAML errors – interesting that it’s also fired due to errors in the measure pass: I’ll have to look out for those too.

  3. asim

    I started getting this exception when I used a control of mine, that had been working fine, in a popup. It seemed unlikely that all of sudden some element was becoming a child of another but I was about to embark on a long hunt through the code.

    Reading this saved me a lot of time but not because I had any inconsistencies in storyboards or animations: in my case it turned out that I was using a uri for Image controls that were no longer valid from a popup – changing this to the full assemby syntax fixed it!

    So it is not just element name references in storyboards, etc, but perhaps it is any kind of failure during instantiation of controls in templates?

    In any case thanks for the tip!

Home Programming Element is already the child of another element – Arghhhhhh