WPF: VisualTreeHelper Find Parent of Specific Type
While working with WPF Visual Tree, one of the common tasks is to find the Parent(Ancestor) or Child of any specific element (DependencyObject).
The following piece of code traverses the visual tree recursively and finds the type of parent you are looking for related to the element you pass in.
For example: If the Visual Tree hierarchy is like this:
- Grid
- StackPanel
- ListBox
You can call the function like this to find the Grid:
FindAncestorpublic static T FindAncestor(DependencyObject dependencyObject) where T : DependencyObject { var parent = VisualTreeHelper.GetParent(dependencyObject); if (parent == null) return null; var parentT = parent as T; return parentT ?? FindAncestor (parent); }
Comments
Post a Comment