Search code examples
.netwpfvisual-tree

Is walking the visual tree bad practice?


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?


Solution

    1. 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).

    2. 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.