winrt代码获取datatemplate中的控件

此方法会递归遍历该DependencyObject的所有VisualChildren(一般用于获取template中未知Name属性但已知类型的控件):

 1  public static ChildControl FindVisualChild<ChildControl>(this DependencyObject DependencyObj)
 2                  where ChildControl : DependencyObject
 3         {
 4             for (int i = 0; i < VisualTreeHelper.GetChildrenCount(DependencyObj); i++)
 5             {
 6                 DependencyObject Child = VisualTreeHelper.GetChild(DependencyObj, i);
 7 
 8                 if (Child != null && Child is ChildControl)
 9                 {
10                     return (ChildControl)Child;
11                 }
12                 else
13                 {
14                     ChildControl ChildOfChild = FindVisualChild<ChildControl>(Child);
15 
16                     if (ChildOfChild != null)
17                     {
18                         return ChildOfChild;
19                     }
20                 }
21             }
22 
23             return null;
24         }
View Code

此方法可获取指定Name属性的子控件(一般用于获取容器控件中已知Name属性的子控件):

 1         public static T GetNamedDescendantOfType<T>(this DependencyObject start, string name) where T : FrameworkElement
 2         {
 3             var descendants = start.GetDescendants();
 4             if (descendants != null)
 5             {
 6                 foreach (FrameworkElement d in descendants)
 7                 {
 8                     if (d.Name.Equals(name))
 9                         return d as T;
10                 }
11             }
12 
13             return null;
14         }
15 
16         public static IEnumerable<DependencyObject> GetDescendants(this DependencyObject start)
17         {
18             var queue = new Queue<DependencyObject>();
19             var count = VisualTreeHelper.GetChildrenCount(start);
20 
21             for (int i = 0; i < count; i++)
22             {
23                 var child = VisualTreeHelper.GetChild(start, i);
24                 yield return child;
25                 queue.Enqueue(child);
26             }
27 
28             while (queue.Count > 0)
29             {
30                 var parent = queue.Dequeue();
31                 var count2 = VisualTreeHelper.GetChildrenCount(parent);
32 
33                 for (int i = 0; i < count2; i++)
34                 {
35                     var child = VisualTreeHelper.GetChild(parent, i);
36                     yield return child;
37                     queue.Enqueue(child);
38                 }
39             }
40         }
View Code

 

转载于:https://www.cnblogs.com/infixu/p/GetChild.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值