在Silverlight项目开发中,经常会把一个独立功能的控件封装成一个UserControl,然后供其他页面或者控件进行调用。前一段时间,在项目中遇到一个问题,需要在同一个页面重复调用多个相同的UserControl控件,然后在父页面中控制这些重复生成的子控件。由于很多控件是动态生成,数量也是动态控制,所以所有的操作都需要使用后台代码进行实现。
在上面的需求中需要用到Silverlight API中的VisualTreeHelper类,对于VisualTreeHelper类,有不少文章已经介绍过,该类可以对Silverlight可视化树进行遍历,该可视化树是逻辑对象树的一个子集。我们可以通过VisualTreeHelper提供的@L_616_28@GetChild(),GetParent()和GetChildrenCount(),分别获取子控件,父控件以及子控件数量。
首先要介绍的Hleper@L_616_28@是GetParentObject@L_616_28@,获取父控件@L_616_28@。该@L_616_28@将根据当前控件,遍历查找其父控件是否存在。参数1是表示当前子控件名,参数2是要查询父控件名;使用VisualTreeHelper.GetParent@L_616_28@获取当前父控件。
2 {
3 DependencyObject parent = VisualTreeHelper.GetParent(obj);
4
5 while (parent != null )
6 7 if is T && (((T)parent).Name == name | .IsNullOrEmpty(Name)))
8 9 return (T)parent;
10 }
11 12 parent VisualTreeHelper.GetParent(parent);
13 14 15 ;
16 17
另外一个Helper@L_616_28@是GetChildObject,获取子控件@L_616_28@。该@L_616_28@将根据当前控件,遍历查找其子控件是否存在。参数1是表示当前父控件名,参数2是要查询子控件名;
最后介绍一个Helper@L_616_28@是GetChildObjects@L_616_28@,该@L_616_28@将把所有子控件作为List集合返回到客户端。其中第一个参数是父控件参数,而第二个参数是特定子控件名称,如果需要遍历全部子控件,第二个参数留空即可。
使用@L_616_28@很简单,首先创建基础控件:
@H_367_301@<
UserControl
x:Class
="SLVisualTreeHelper.MainPage"
2
xmlns
="http://scheR_866_11845@as.microsoft.com/winfx/2006/xaml/presentation"
3
xmlns:x
="http://scheR_866_11845@as.microsoft.com/winfx/2006/xaml"
4
xmlns:d
="http://scheR_866_11845@as.microsoft.com/expression/blend/2008"
5
xmlns:mc
="http://scheR_866_11845@as.openxmlformats.org/markup-compatibility/2006"
6
@H_689_316@mc:Ignorable
="d"
7
d:DesignHeight
="300"
d:DesignWidth
="400"
>
Grid
x:Name
="LayoutRoot"
BACkground
="White"
Grid.RowDeFinitions
RowDeFinition
Height
="Auto"
></
RowDeFinition
="*"
</
StackPanel
="spDemoPanel"
Orientation
="Vertical"
Grid.Row
="0"
TextBlock
@H_689_316@margin
="5"
获取子控件和父控件演示
TextBlock
专注Silverlight技术交流
博客:http//jv9.cnblogs.com
Button
="btDemoButton"
Width
="120"
Height
="40"
Content
="获取所有控件"
Click
="btDemoButton_Click"
HorizontalAlignment
="Left"
Margin
/>
="btModifyChild"
="修改布局控件背景"
="btModifyChild_Click"
="btModifyChilds"
="批量修改控件字体尺寸"
="btModifyChilds_Click"
StackPanel
="spResult"
="1"
="tbResult"
25
26
27
Grid
28
UserControl
29
partial class MainPage : UserControl
MainPage()
InitializeComponent();
private void btDemoButton_Click( object sender,RoutedEventArgs E)
Globals VTHelper Globals();
StackPanel sp VTHelper.GetChildObject ( this .LayoutRoot,0)">" spDemoPanel " );
Grid layoutGrid VTHelper.GetParentObject .spDemoPanel,0)">LayoutRoot textblock VTHelper.GetChildObjects (sp (layoutGrid (textblock.Count tbResult.Text 包含TextBlock控件数量为: + textblock.Count.ToString() \n += 获取父控件成功....\n ;
29 30 获取子控件成功....\n 31 32 33 34 btModifyChild_Click( 35 36 37 38 sp.BACkground SolidColorBrush(Colors.PurplE);
39 40 41 btModifyChilds_Click( 42 43 44 45 foreach (TextBlock tmpTextblock in textblock)
46 47 tmpTextblock.FontSize 48 49 50 51 }
在线演示:
最后是源代码下载,项目是VS2010+Silverlight 4,
点击下载 |