Did WPF 4.5 parent-child behavior change: we can n

2019-03-13 00:03发布

问题:

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.

回答1:

There are times when it makes sense for a child to have more than one logical parent, for instance in layout-to-layout animation. I'm guessing the WPF team decided it was time to let developers decide when and how to use this instead of disallowing it.