Posts

Showing posts with the label Find Parent

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  (pare...