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.
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.