in Uncategorized

Avalon: Visual Tree vs. Logical Tree Trickiness

Someone asked a good question in the WinFx newsgroups about how to go from a the result of a hit test (via UIElement::InputHitTest) to a Button. Now InputHitTest returns IInputElement which you can then cast to FrameworkElement. At first you might think you can just walk up the logical tree from there using FrameworkElement::Parent until you run into the Button, but here’s where the trickyness comes in: the logical tree of the Button is separate from the logical tree of whatever contains it, but the Button’s visual “branch” is merged into the main visual tree. Therefore once you hit the top level element of the Button’s logical tree (Grid if you’re using the default style), it will have no Parent of its own.

So then, how do you get at the Button when coming up through the tree in this case? The answer to that is the FrameworkElement::StyledParent property. This property returns the element whose Style.VisualTree caused this visual “branch” to be created.

Disclaimer: This is my interpretation and understanding based on research and experimentation. Some of my terms may be wrong and I may not be explaining everything 100% correctly.

Leave a comment


  • Related Content by Tag