Advertisement
sixlsix

find control parent/child

Feb 12th, 2015
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.77 KB | None | 0 0
  1. //*****************************************
  2. //  example use:
  3. //
  4. //  var tb = null as TextBox;
  5. //  tb = FindVisualChild<TextBox>(container as DependencyObject, "tbTrigger");
  6. //***********************************
  7.  
  8. public static T FindVisualChild<T>(DependencyObject depObj, string objectName) where T : DependencyObject
  9.         {
  10.             if (depObj != null)
  11.             {
  12.                 for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
  13.                 {
  14.                     DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
  15.                     if (child != null && child is T)
  16.                     {
  17.                         var name = child.ReadLocalValue(NameProperty);
  18.  
  19.                         if (name.ToString() == objectName)
  20.                             return (T)child;
  21.                     }
  22.  
  23.                     T childItem = FindVisualChild<T>(child, objectName);
  24.                     if (childItem != null) return childItem;
  25.                 }
  26.             }
  27.             return null;
  28.         }
  29.  
  30.         public static T FindVisualParent<T>(DependencyObject depObj) where T : DependencyObject
  31.         {
  32.             bool IsParentFound = false;
  33.             DependencyObject parent;
  34.  
  35.             if (depObj != null)
  36.             {
  37.                 while (!IsParentFound)
  38.                 {
  39.                     parent = VisualTreeHelper.GetParent(depObj);
  40.                     if (parent != null && parent is T)
  41.                     {
  42.                         IsParentFound = true;
  43.                         return (T)parent;
  44.                     }
  45.  
  46.                     T parentItem = FindVisualParent<T>(parent);
  47.                     if (parentItem != null) return parentItem;
  48.                 }
  49.             }
  50.             return null;
  51.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement