Saturday, 30 March 2013

WPF - Find Parent by Type

Building on from my earlier post here I thought I'd show how we can use VisualTreeHelper to go the other way up the tree and find a parent of a specified type.

To do this we will be using the following method of VisualTreeHelper:"

DependencyObject GetParent(DependencyObject reference);

This method quite simply returns the parent object of the specified visual object. We can use this method like so:

  1. public static T GetVisualParent<T>(this DependencyObject child) where T : Visual
  2. {
  3.     Visual parentObject = VisualTreeHelper.GetParent(child) as Visual;
  4.     if (parentObject == null) return null;
  5.     return parentObject is T ? parentObject as T : GetVisualParent<T>(parentObject);
  6. }

We call VisualTreeHelper.GetParent and try cast the return value as a Visual, if the parent object is of type Visual we check if it our required type, if it is we return this object otherwise we pass the object into our method again so that we iterate up the visual tree. We can call this method like so:

  1. private void GetVisualParentTest(ScrollViewer sv)
  2. {
  3.     ListView lvw = sv.GetVisualParent<ListView>();
  4. }

No comments:

Post a comment