wpf获取父控件、子控件

1、获取父控件

调用方法:Grid layoutGrid = VTHelper.GetParentObject<Grid>(this.spDemoPanel, "LayoutRoot");

 1 public T GetParentObject<T>(DependencyObject obj, string name) where T : FrameworkElement
 2 {
 3     DependencyObject parent = VisualTreeHelper.GetParent(obj);
 4     while (parent != null)
 5     {
 6         if (parent is T && (((T)parent).Name == name || string.IsNullOrEmpty(name)))
 7         {
 8            return (T)parent;
 9         }
10         parent = VisualTreeHelper.GetParent(parent);
11     }
12     return null;
13}

 

2、获取子控件

调用方法:StackPanel sp = VTHelper.GetChildObject<StackPanel>(this.LayoutRoot, "spDemoPanel");

 1 public T GetChildObject<T>(DependencyObject obj, string name) where T : FrameworkElement
 2           {
 3               DependencyObject child = null;
 4               T grandChild = null;
 5               for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
 6               {
 7                  child = VisualTreeHelper.GetChild(obj, i);
 8                  if (child is T && (((T)child).Name == name || string.IsNullOrEmpty(name)))
 9                  {
10                      return (T)child;
11                  }
12                  else
13                  {
14                      grandChild = GetChildObject<T>(child, name);
15                      if (grandChild != null)
16                      return grandChild;
17                  }
18              }
19              return null;
20          }

 

 

 

3、获取所有子控件

调用方法:List<TextBlock> textblock = VTHelper.GetChildObjects<TextBlock>(this.LayoutRoot, "");

在表格中的控件:List<TextBox> listTextBox = GetChildObjects<TextBox>(radGridView_File.ItemContainerGenerator.ContainerFromItem(radGridView_File.SelectedItems[0]), "");

 1 public List<T> GetChildObjects<T>(DependencyObject obj, string name) where T : FrameworkElement
 2           {
 3               DependencyObject child = null;
 4               List<T> childList = new List<T>();
 5               for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
 6               {
 7                  child = VisualTreeHelper.GetChild(obj, i);
 8                  if (child is T && (((T)child).Name == name || string.IsNullOrEmpty(name)))
 9                  {
10                      childList.Add((T)child);
11                  }
12                 childList.AddRange(GetChildObjects<T>(child,""));
13               }
14              return childList;
15          }

 

 

 

posted @ 2013-08-02 23:24  夜曲984  阅读(9716)  评论(0编辑  收藏  举报