积极答复者
Windows Phone 7中怎么查找DataTemplate中的控件?

问题
-
我在LongListSelector控件有用DataTemplate布局联系人如下
<DataTemplate x:Key="ItemsTemplate"> <Grid Margin="0,0,0,20" > <Grid.ColumnDefinitions> <ColumnDefinition Width="90"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="60"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="0.3*"/> </Grid.RowDefinitions> <!-- <Image x:Name="imgHead" Source="/Images/head.jpg" Grid.Row="0" Grid.RowSpan="2" Width="90" Height="90"/>--> <TextBlock x:Name="tbName" Grid.Row="0" Grid.Column="1" FontSize="38" TextAlignment="Left" VerticalAlignment="Center" TextWrapping="Wrap" Text="{Binding Name}" /> <TextBlock x:Name="tbPhone" Grid.Row="1" Grid.Column="1" FontSize="25" TextAlignment="Left" VerticalAlignment="Center" TextWrapping="Wrap" Text="{Binding Phone}" /> <CheckBox Grid.Row="0" Grid.Column="2" Grid.RowSpan="2" IsChecked="{Binding IsCheck, Mode=TwoWay}" x:Name="cbCheck"/> </Grid> </DataTemplate>
在后台代码中我用下面方法获取选中的CheckBoxstring phones = string.Empty; sb.Clear(); if (VisualTreeHelper.GetChildrenCount(lsAllContacts) > 0) { IEnumerable<Grid> AllGrids = FindChildren<Grid>(this.lsAllContacts);//得到所有的Grid foreach (var grid in AllGrids.ToList()) { object objTbPhone = grid.FindName("tbPhone"); if (objTbPhone != null) { object objCheck = grid.FindName("cbCheck"); object objName = grid.FindName("tbName"); if (objCheck != null) { if (((CheckBox)objCheck).IsChecked == true) { smsComposeTask.To += ((TextBlock)objTbPhone).Text; sb.Append(((TextBlock)objName).Text + ";"); } } } } }
FindChildren方法public IEnumerable<T> FindChildren<T>(DependencyObject parent) where T : class { var count = VisualTreeHelper.GetChildrenCount(parent); if (count > 0) { for (var i = 0; i < count; i++) { var child = VisualTreeHelper.GetChild(parent, i); var t = child as T; if (t != null) yield return t; var children = FindChildren<T>(child); foreach (var item in children) yield return item; } } }
用这种方法得不到所有的CheckBox,只能得到部份,不知道是为什么,程序中是递归了子控件的呀。