2012-11-26 28 views
1

我想訪問WPF列表框中的所有按鈕,這裏是我的xaml代碼。查找WPF列表框中的所有控件

<Grid> 
    <ScrollViewer x:Name="myScrollViewer" HorizontalScrollBarVisibility="Disabled" MouseDown="myStackPanel_MouseDown" MouseUp="myScrollViewer_MouseMove" VerticalScrollBarVisibility="Hidden" Height="435" BorderBrush="{x:Null}" Width="250" Margin="0,-4,-4,-4" ScrollChanged="scrollerVideoCategory_ScrollChanged"> 
     <StackPanel Orientation="Vertical" Name="StackPanleEmployee" Margin="40,0,0,0" MouseDown="myStackPanel_MouseDown" MouseUp="myScrollViewer_MouseMove" Loaded="StackPanleVideoCategory_Loaded" > 
      <ListBox x:Name="ListBoxEmployeVideoType" MouseDown="myStackPanel_MouseDown" MouseUp="myScrollViewer_MouseMove" BorderThickness="0,1,0,0" BorderBrush="#E2E2E2"> 
       <ListBox.ItemTemplate> 
        <DataTemplate> 
         <StackPanel Orientation="Vertical" Width="200" Name="myStackPanel" MouseDown="myStackPanel_MouseDown" MouseUp="myScrollViewer_MouseMove" > 
          <Button VerticalAlignment="Center" Style="{StaticResource ButtonVideoTabItemDefault}" MouseUp="b_MouseMove" Tag="{Binding Path}" Content="{Binding Name}" Name="btnSubCategory" Click="btnVideoCategorySelection_Click"></Button> 
          <Separator Background="#E2E2E2" Margin="0"/> 
         </StackPanel> 
        </DataTemplate> 
       </ListBox.ItemTemplate> 
      </ListBox> 
     </StackPanel> 
    </ScrollViewer> 
</Grid> 

有沒有想法?

+0

您忘記了發佈代碼 – 888

回答

0

您可以使用VisualTreeHelper或LogicalTreeHelper類的GetChildren()方法。 Ref SDK

可視化樹代表在UI中呈現的所有元素,而UI的邏輯樹基本結構。你可以閱讀關於使用的詳細信息here

希望這會有所幫助。

3

財產以後這樣就可以做的伎倆

 /// <summary> 
     /// Finds the visual child. 
     /// </summary> 
     /// <typeparam name="childItem">The type of the child item.</typeparam> 
     /// <param name="obj">The obj.</param> 
     /// <returns></returns> 
     private IEnumerable<T> FindVisualChildren<T>(DependencyObject obj) where T : DependencyObject 
     { 
      for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) 
      { 
       DependencyObject child = VisualTreeHelper.GetChild(obj, i); 
       if (child != null && child is T) 
       { 
        yield return (T)child; 
       } 
       else 
       { 
        var childOfChild = FindVisualChildren<T>(child); 
        if (childOfChild != null) 
        { 
         foreach (var subchild in childOfChild) 
         { 
          yield return subchild; 
         } 
        } 
       } 
      } 
     } 

只是聲明你想要的類型,幷包含這些

var buttons = FindVisualChildren<Button>(ListBoxEmployeVideoType).ToList(); 

控制這僅僅是一個簡單的例子,並可以擴展到您的需要。