WPF 4.5 父子行为是否发生变化:我们现在可以毫无例外地将子项添加到另一个父项? [英] Did WPF 4.5 parent-child behavior change: we can now add a child to another parent without exception?

查看:17
本文介绍了WPF 4.5 父子行为是否发生变化:我们现在可以毫无例外地将子项添加到另一个父项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 .Net 4.0 中,以下代码抛出一个 InvalidOperationException 消息指定的元素已经是另一个元素的逻辑子元素.先断开它."

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

但是,在安装了 .Net 4.5 的机器上运行此代码导致没有抛出异常.这似乎会导致可视化树出现一些奇怪的状态,显示为不正确的 UI.

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.

为什么没有例外? throw 语句似乎仍然存在于 .Net 4.5 FrameworkElement.AddLogicalChild 中.什么会导致它不被抛出?

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?

我很高兴接受行为改变是有充分理由的,我必须改变我的编码,但是,就目前而言,当显式异常时,带有损坏 UI 的无声失败似乎是从强异常倒退了一步忘记将 FrameworkElement 与逻辑树断开连接.

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.

推荐答案

有时候一个孩子有多个逻辑父级是有意义的,例如在 布局到布局动画.我猜 WPF 团队决定是时候让开发人员决定何时以及如何使用它而不是禁止它.

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.

这篇关于WPF 4.5 父子行为是否发生变化:我们现在可以毫无例外地将子项添加到另一个父项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆