2010-09-16 4 views
0

Я хочу проверить некоторые дочерние элементы в моей WPF-форме. В WindowsForms, что было довольно легко с (например):VB.NET - для каждого в WPF-элемента управления

For Each control as Textbox in Me 
control.text = "hello people" 
Next 

Как сделать это в WPF в моем XAML.VB-файл? У меня есть список с некоторыми дочерними элементами, которые я хочу проанализировать.

Greetz и спасибо за ваши идеи!

ответ

4

Это зависит. Предположим, что у вас есть ListBox определяется как:

<ListBox x:Name="listBox"> 
    <ListBoxItem>Item1</ListBoxItem> 
    <ListBoxItem>Item2</ListBoxItem> 
    <ListBoxItem>Item3</ListBoxItem> 
</ListBox> 

Вы можете получить ListBoxItems в него просто переборе коллекции предметов, как, например:

For Each x As ListBoxItem In Me.listBox.Items 
    Console.WriteLine(x.Content.ToString()) 
Next 

Однако, это не будет работать, если элементы в ListBox был определен с помощью свойства ItemsSource. Таким образом, если элементы определены следующим образом:

Dim itemsSource As New List(Of Object) 
    itemsSource.Add("Object1") 
    itemsSource.Add(200D) 
    itemsSource.Add(DateTime.Now) 
    Me.listBox.ItemsSource = itemsSource 

вам придется использовать ItemContainerGenerator, чтобы получить фактическое ListBoxItem.

For Each x In Me.listBox.Items 
     Dim item As ListBoxItem = DirectCast(Me.listBox.ItemContainerGenerator.ContainerFromItem(x), ListBoxItem) 
     Console.WriteLine(item.Content.ToString()) 
    Next 

Теперь приведенные выше примеры относятся к элементу управления ListBox. Если вам нужен способ получить все элементы во всем Визуальном дереве данного элемента управления (например, Окно), вам придется использовать VisualTreeHelper.GetChild (как предложил Брайан).

В любом случае, вот небольшой пример, который я написал, который может вам помочь. Он содержит все, что я описал выше.

XAML:

<Window x:Class="MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded"> 
    <StackPanel x:Name="sp"> 
     <ListBox x:Name="listBox"> 
      <ListBoxItem>Item1</ListBoxItem> 
      <ListBoxItem>Item2</ListBoxItem> 
      <ListBoxItem>Item3</ListBoxItem> 
     </ListBox> 

     <Button x:Name="btnChange" Click="btnChange_Click">Change ItemsSource</Button> 
     <Button x:Name="btnPrint" Click="btnPrint_Click">Print Items</Button> 

     <Button x:Name="btnPrintVisualTree" Click="btnPrintVisualTree_Click">Print Visual Tree</Button> 
    </StackPanel> 
</Window> 

Code-за:

Class MainWindow 


    Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) 

     'Get all ListBoxItems 
     For Each x As ListBoxItem In Me.listBox.Items 
      Console.WriteLine(x.Content.ToString()) 
     Next 

     'Get all items in the StackPanel 
     For Each y As UIElement In Me.sp.Children 
      Console.WriteLine(y.ToString()) 
     Next 

    End Sub 

    Private Sub btnChange_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) 
     'Set an ItemsSource for the ListBox 

     Me.listBox.Items.Clear() 

     Dim itemsSource As New List(Of Object) 
     itemsSource.Add("Object1") 
     itemsSource.Add(200D) 
     itemsSource.Add(DateTime.Now) 
     Me.listBox.ItemsSource = itemsSource 
    End Sub 

    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) 

     'Print the items within the ListBox 
     For Each x In Me.listBox.Items 
      Dim item As ListBoxItem = DirectCast(Me.listBox.ItemContainerGenerator.ContainerFromItem(x), ListBoxItem) 
      Console.WriteLine(item.Content.ToString()) 
     Next 

    End Sub 

    Private Sub btnPrintVisualTree_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) 
     PrintVisualTreeRecursive(Me) 
    End Sub 

    Private Sub PrintVisualTreeRecursive(ByVal parent As DependencyObject) 

     Console.WriteLine(parent.ToString()) 

     Dim count As Integer = VisualTreeHelper.GetChildrenCount(parent) 
     If count > 0 Then 
      For n As Integer = 0 To count - 1 
       Dim child As DependencyObject = VisualTreeHelper.GetChild(parent, n) 
       PrintVisualTreeRecursive(child) 
      Next 
     End If 
    End Sub 

End Class 
2

Вам нужно будет использовать метод VisualTreeHelper.GetChild и вызвать его рекурсивно для спускания дерева. Если вы знаете имя элемента управления, которое вы ищете, вы можете использовать метод FrameworkElement.FindName. В this question есть дополнительная информация с большим количеством опций и пример кода.

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