WP8.1程序开发,可视树VisualTreeHelper类的使用

对于可视树的使用,很久之前就接触了,

  一方面当时知识太浅根本看不懂,就放下没看了;

  另一方面,也没用到,就没往这方面努力研究学习;

  现在好了,遇到问题了,正好涉及到VisualTreeHelper的使用,就开始找有关方面的示例学习,经过断断续续地学习,算是明白了一点用法,现在就来讲一下个人的理解:

1.首先,在名为"fv"的FlipView控件内有一个名为"img"的Image控件,前台代码如下:

1 <FlipView x:Name="fv" Margin="0 0 0 0">
2                 <FlipView.ItemTemplate>
3                     <DataTemplate>
4                         <Image x:Name="img" Margin="0 0 0 0"  Source="{Binding ImageSource}" Stretch="Uniform"  ></Image>
5                        
6                     </DataTemplate>
7                 </FlipView.ItemTemplate>
8             </FlipView>

2.接下来,我们要用VisualTreeHelper类,通过遍历来找名为"img"的Image控件(如果不用此方法,在后台不能直接用"img"获得Image控件),遍历方法为:


 1 public static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject
 2         {
 3             for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
 4             {
 5                 var child = VisualTreeHelper.GetChild(parent, i);
 6                 string controlName = child.GetValue(Control.NameProperty) as string;
 7                 if (controlName == name)
 8                 {
 9                     return child as T;
10                 }
11                 else
12                 {
13                     T result = FindVisualChildByName<T>(child, name);
14                     if (result != null)
15                         return result;
16                 }
17             }
18             return null;
19         }

 


3.最后,我们要使用上方面写的方法,来得到Image控件:

 Image v = FindVisualChildByName<Image>(fv, "img");

4.这样,我们就得到了FlipView控件内有一个名为"img"的Image控件 v的实例,这样,我们就可以对实例v进行一系列的操作;

  当然,这个示例是通过控件名来遍历出控件的,还有通过控件的类型遍历得到所需要的控件,那个还没用过,感觉没通过名字得到的精准,之后用到了再讲。

 

posted on 2016-02-13 20:54  legendofhungrywolf  阅读(143)  评论(0编辑  收藏  举报