Visual Tree Parent Searcher


/ Published in: C#
Save to your folder(s)

Code to find the parent of a specific type for an object in silverlight


Copy this code and paste it in your HTML
  1. using System.Windows;
  2. using System.Windows.Media;
  3.  
  4. namespace Utils
  5. {
  6. /// <summary>
  7. /// The class contains the externsion helper methods
  8. /// for the visual tree
  9. /// </summary>
  10. public static class VisualTreeExtensions
  11. {
  12. /// <summary>
  13. /// This method will return the parent object of a specific type for a
  14. /// particular element
  15. /// </summary>
  16. /// <typeparam name="T">the type of the parent we are looking for</typeparam>
  17. /// <param name="element">the element on which we are looking for the parent</param>
  18. /// <returns>if properly found then the parent object otherwise null</returns>
  19. public static T GetParent<T>(this DependencyObject element) where T : DependencyObject
  20. {
  21. var parent = VisualTreeHelper.GetParent(element);
  22. if (parent == null)
  23. {
  24. return null;
  25. }
  26. else if (parent is T)
  27. {
  28. return (T)parent;
  29. }
  30. else
  31. {
  32. return parent.GetParent<T>();
  33. }
  34. }
  35.  
  36. }
  37. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.