By Michael Flanakin
@ 10:20 AM
:: 3365 Views
:: Digg it!
I recently got an error that didn't seem to make a lot of sense to me...
Specified element is already the logical child of another element.
It sounds pretty straight-forward, and I'm sure it normally is, but the real oddity is that the same section of code was working not too much before the latest run. I did a few searches and saw a number of people trying to address the problem the error actually talks about, reusing control instances. This seems to be more of a problem when you're programmatically adding controls, which I wasn't doing, so that made even less sense. Despite all this, I changed my code around, re-ran the app, and was rid of the problem. All good, right? Wrong.
The next problem I had was a stack overflow (in another section of code). Ok, two strange errors in a row? Something's up. All I really remember changing since the last run was hooking up some command bindings. The call stack revealed that the problem was in a constructor of a user control on my main window. I removed some code from there, ultimately killing all functionality, but that didn't do it. I then went back to the main window and looked at the XAML. What could be triggering the repeated calls to the constructor? I then found a spot where I was doing some data binding. I definitely remember adding this recently and know I did it only half-understanding how it worked, so I removed it and all was back to normal.
That's pretty much when it hit me. The controls were being added multiple times because the constructor was being called successively. Bah! I went back and changed the original code I modified back to the way it was because I felt it was much more concise. Everything still worked, so I know that was the problem.
Basically, what I'm getting at is, if you get this error and you don't know why the heck it came up, comment out the offending code and try to re-run the app. If you get a stack overflow when calling InitializeComponent(), then the commented out code isn't the problem. Take a look at your XAML. Unfortunately, I don't know enough about how all that gets hooked up right now, so I can't give a definitive suggestion on where to start, but bindings are a pretty obvious one, so check there.