Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Did WPF 4.5 parent-child behavior change: we can now add a child to another parent without exception?

Tags:

.net

wpf

.net-4.5

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.

like image 653
codekaizen Avatar asked Sep 04 '12 20:09

codekaizen


1 Answers

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.

like image 64
Nigel Shaw Avatar answered Nov 18 '22 09:11

Nigel Shaw