2013-09-01 12 views
1

Я пытаюсь найти дочерний элемент LongListSelector. Вот мой UIНайти дочерние элементы управления телефона LongListSelector Windows

<phone:PhoneApplicationPage.Resources> 
    <DataTemplate x:Key="ItemTemplate"> 
     <StackPanel Orientation="Horizontal"> 
      <Image Source="{Binding Photo}" Height="100" Width="100"/> 
      <StackPanel>      
       <TextBlock FontFamily="Segoe UI Semilight" Padding="9" Foreground="#313131" Width="330" TextWrapping="Wrap" Name="lblMessage" Text="{Binding Message}" FontSize="26" /> 
       <Button HorizontalAlignment="Left" Width="130" FontFamily="Segoe UI Semilight" BorderThickness="0.5" BorderBrush="#D62429" Content="Button1" Foreground="#313131"></Button> 
       <Button Margin="15,-65,0,0" Width="120" FontFamily="Segoe UI Semilight" BorderThickness="0.5" BorderBrush="#D62429" Content="Button2" Foreground="#313131"></Button>      
      </StackPanel>  
      <StackPanel> 
       <RadioButton Name="Rdb1"/> 
       <RadioButton Name="Rdb2"/> 
      </StackPanel>   
     </StackPanel> 
    </DataTemplate> 

    <DataTemplate x:Key="ListHeader"> 
     <Border Background="#D62429" Opacity="0.8" Height="50"> 
      <TextBlock Name="txtHeader" Text="Long List Header" VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="Black" FontFamily="Segoe UI Semilight"/> 
     </Border> 
    </DataTemplate> 
</phone:PhoneApplicationPage.Resources> 

<Grid x:Name="LayoutRoot" Background="White">  
    <Grid.RowDefinitions> 
     <RowDefinition Height="Auto"/> 
     <RowDefinition Height="*"/> 
    </Grid.RowDefinitions> 
    <!--<Grid x:Name="gvHeader" Width="480" Height="70" Grid.Row="0" Canvas.ZIndex="1"></Grid>--> 
    <!--Pivot Control--> 
    <phone:Pivot Grid.Row="1" Name="pivotItems" Title="Welcome">    
     <phone:PivotItem FontFamily="Segoe WP Light" Header="item1"> 
      <Grid x:Name="item2" Grid.Row="1"> 
       <phone:LongListSelector ItemsSource="{Binding ListModel}" x:Name="longListSelector" 
       IsGroupingEnabled="True" LayoutMode="List" HideEmptyGroups="False"           
       ListHeaderTemplate="{StaticResource ListHeader}"/> 
      </Grid> 
     </phone:PivotItem> 

     <!--Pivot item two--> 
     <phone:PivotItem Header="item2"> 

     </phone:PivotItem> 
    </phone:Pivot> 
</Grid> 

Здесь я хочу найти TextBlock контроль ListHeader. Я использую этот код, чтобы найти элемент управления. но ничего не получаю.

TextBlock txtBlockHeader = FindFirstElementInVisualTree<TextBlock>(this.longListSelector.ListHeaderTemplate); 

private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject 
{ 
    var count = VisualTreeHelper.GetChildrenCount(parentElement); 
    if (count == 0) 
     return null; 

    for (int i = 0; i < count; i++) 
    { 
     var child = VisualTreeHelper.GetChild(parentElement, i); 

     if (child != null && child is T) 
     { 
      return (T)child; 
     } 
     else 
     { 
      var result = FindFirstElementInVisualTree<T>(child); 
      if (result != null) 
       return result; 

     } 
    } 
    return null; 
} 

Как я могу найти TextBlock от ListHeader? Что случилось в моем коде?

ответ

2

Это потому, что ListHeaderTemplate возвращает данные. Паттерн данных, как показывает его название, представляет собой шаблон: план, указывающий, какие элементы управления должны быть построены и как. Это не фактический контроль.

Я не знаю, доступен ли экземпляр шаблона в LongListSelector. Тем не менее, вы можете обойти эту проблему с помощью ListHeader вместо:

<phone:LongListSelector ItemsSource="{Binding ListModel}" x:Name="longListSelector" 
     IsGroupingEnabled="True" LayoutMode="List" HideEmptyGroups="False"      
     ItemTemplate="{StaticResource ItemTemplate}"> 
     <phone:LongListSelector.ListHeader> 
      <Border Background="#D62429" Opacity="0.8" Height="50"> 
       <TextBlock Name="txtHeader" Text="Long List Header" VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="Black" FontFamily="Segoe UI Semilight"/> 
      </Border> 
     </phone:LongListSelector.ListHeader> 
    </phone:LongListSelector> 

Затем вы можете вызвать свой метод, используя то же ListHeader свойства:

FindFirstElementInVisualTree<TextBlock>((FrameworkElement)this.longListSelector.ListHeader); 

или даже используя непосредственно имя текстового поля в:

this.txtHeader.Text = "Hello world!"; 
+0

Он отлично работает, когда я устанавливаю ItemSource в longListSelector. Но это не работает, когда я не устанавливал ItemSource, он не показывает заголовок. –

+0

@Ajay Но вы видите заголовок, когда вы не устанавливаете ItemSource и не используете 'ListHeaderTemplate' вместо' ListHeader'? –

+0

Когда я использую ListHeaderTemplate, я не могу напрямую обращаться к txtHeader. –

Смежные вопросы