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:
FindAncestor((DependencyObject)ListBox);


public static T FindAncestor(DependencyObject dependencyObject)
            where T : DependencyObject
        {
            var parent = VisualTreeHelper.GetParent(dependencyObject);
 
            if (parent == nullreturn null;
 
            var parentT = parent as T;
            return parentT ?? FindAncestor(parent);
        }

Comments

Popular posts from this blog

WPF How to Dispose ViewModel when the associated UserControl (Not Window) closes?

C# How to unit test Dispatcher

WPF: How to Deep Copy WPF object (e.g. UIElement) ?