wpf 查找父元素、子元素方法

 1         /// <summary>
 2         /// 根据类型查找子元素
 3         /// </summary>
 4         /// <typeparam name="T"></typeparam>
 5         /// <param name="obj"></param>
 6         /// <param name="typename"></param>
 7         /// <returns></returns>
 8         public List<T> GetChildObjects<T>(DependencyObject obj, Type typename) where T : FrameworkElement
 9         {
10             DependencyObject child = null;
11             List<T> childList = new List<T>();
12 
13             for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
14             {
15                 child = VisualTreeHelper.GetChild(obj, i);
16 
17                 if (child is T && (((T)child).GetType() == typename))
18                 {
19                     childList.Add((T)child);
20                 }
21                 childList.AddRange(GetChildObjects<T>(child, typename));
22             }
23             return childList;
24         }

调用 1 List<StackPanel> initToolBarWeChatUserSp = GetChildObjects<StackPanel>(name, typeof(StackPanel)); 

 

 1         /// <summary>
 2         /// 查找父元素
 3         /// </summary>
 4         /// <typeparam name="T"></typeparam>
 5         /// <param name="obj"></param>
 6         /// <param name="name"></param>
 7         /// <returns></returns>
 8         public static T FindParent<T>(DependencyObject i_dp) where T : DependencyObject
 9         {
10             DependencyObject dobj = (DependencyObject)VisualTreeHelper.GetParent(i_dp);
11             if (dobj != null)
12             {
13                 if (dobj is T)
14                 {
15                     return (T)dobj;
16                 }
17                 else
18                 {
19                     dobj = FindParent<T>(dobj);
20                     if (dobj != null && dobj is T)
21                     {
22                         return (T)dobj;
23                     }
24                 }
25             }
26             return null;
27         }

调用 1 Border tbBorder = FindParent<Border>(name); 

  

转载于:https://www.cnblogs.com/SARU-52098/p/6815907.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值