In .Net 4.0 the following code throws an InvalidOperationException
with the message "Specified element is already the logical child of another element. Disconnect it first."
var parent = new System.Windows.Controls.ContentControl();
var child = new System.Windows.Controls.Button();
parent.Content = child;
var parent2 = new System.Windows.Controls.ContentControl();
parent2.Content = child; // throws InvalidOperationException in .Net 4.0, not in 4.5
However, running this code on a machine with .Net 4.5 installed results in no exception being thrown. This appears to cause the visual tree to have some strange state which shows up as an incorrect UI.
Why no exception? The throw
statement appears to be still present in .Net 4.5 FrameworkElement.AddLogicalChild
. What would cause it to be not thrown?
I'm happy to accept that the behavior changed for a good reason, and I have to change my coding, however, as it stands, the silent fail with corrupt UI seems like a step backward from the strong exception when the explicit disconnection of a FrameworkElement
from the logical tree was forgotton.