Programmatically Find an Ancestor in the Visual Tree
Posted on 2012-11-25 10:59 Alex Geng 阅读(133) 评论(0) 收藏 举报If you are a child element of a user interface and you want to access data from a parent element, but you don't know how many levels up that elemens is, it's the best solution to navigate up the tree until it finds an element of the requested type.
This helper does excactly this. You can use almost the same code to navigate through the logical tree.
public static class VisualTreeHelperExtensions { public static T FindAncestor<T>(DependencyObject dependencyObject) where T : class { DependencyObject target = dependencyObject; do { target = VisualTreeHelper.GetParent(target); } while (target != null && !(target is T)); return target as T; } }
The following example shows how to use the helper. It starts at this and navigates up the visual tree until it finds an element of type Grid. If the helper reaches the root element of the tree, it returns null.
var grid = VisualTreeHelperExtensions.FindAncestor<Grid>(this);
浙公网安备 33010602011771号