可步行可视树是不好的做法?可视、做法、不好

2023-09-05 00:44:44 作者:花·祭

最近我看过关于走可视化树是不好的做法有些意见(这里例如),但我还没有看到或找到一个理由,为什么这将是不好的做法。

在一个项目,我的工作有相当多的树走,所以我不知道我是否应该去改变这一切别的东西还是让它是因为它是。

所以,我想我在这里的主要问题是,如果视觉树的遍历还真是不好的做法,更重要的是,如果是,为什么的?

此外,在哪里(如果有的话?)会是好走可视化树?

解决方案

走一个可视化树往往达闯入通过WPF自然机制提供的抽象,手动执行什么样的框架应该由自己(通过XAML声明,绑定等)做的。这是一个黑客,简单地说。有时它表示一个不知道如何使用WPF正常。 (这是很难确属自用的,顺便说一句)。

您无法真正知道在任何时候都可视化树是否完整与否; WPF可能没有产生所有的控制,但(例如,在填​​充有许多项目的列表)。为了解决这个问题,你需要实现的保障措施,处理 LayoutUpdated 事件等,使您的code过于复杂。

世界上最 阴损 的树,不排毒不夺取营养,却被很多地方禁止种植

Lately I've seen some comments about walking the visual tree being bad practice (here for instance), but I haven't seen or found a reason for why this would be bad practice.

In a project I'm working on there's quite a bit of tree walking, so I'm wondering if I should bother changing all this to something else or just let it be as it is.

So, I guess my main question here is if visual tree walking really is bad practice, and more importantly, if it is, why?

Also, where (if at all?) would it be ok to walk the visual tree?

解决方案

Walking a visual tree often amounts to breaking into the abstraction provided by WPF "natural" mechanisms, enforcing manually what the framework should be doing by itself (via XAML declarations, databinding etc.). It's a hack, simply put. Sometimes it indicates that one wasn't sure how to use WPF properly. (Which is difficult to use indeed, by the way).

You can't really know at all times whether the visual tree is complete or not; WPF may not have generated all the controls yet (for example, while populating a list with many items). In order to solve this, you need to implement safeguards, handle LayoutUpdated events etc., which makes your code overly complex.