방법: DataTemplate에서 생성된 요소 찾기

이 예제는 DataTemplate에 의해 생성되는 요소를 찾는 방법을 보여 줍니다.

예제

이 예제에는 일부 XML 데이터에 바인딩된 ListBox가 있습니다.

<ListBox Name="myListBox" ItemTemplate="{StaticResource myDataTemplate}"
         IsSynchronizedWithCurrentItem="True">
  <ListBox.ItemsSource>
    <Binding Source="{StaticResource InventoryData}" XPath="Books/Book"/>
  </ListBox.ItemsSource>
</ListBox>

ListBox는 다음 DataTemplate을 사용합니다.

<DataTemplate x:Key="myDataTemplate">
  <TextBlock Name="textBlock" FontSize="14" Foreground="Blue">
    <TextBlock.Text>
      <Binding XPath="Title"/>
    </TextBlock.Text>
  </TextBlock>
</DataTemplate>

특정 ListBoxItemDataTemplate에 의해 생성된 TextBlock 요소를 검색하려면 ListBoxItem을 가져와 해당 ListBoxItem 내에서 ContentPresenter를 찾은 다음 해당 ContentPresenter에서 설정된 DataTemplate에서 FindName을 호출해야 합니다. 다음 예제는 이러한 단계를 수행하는 방법을 보여 줍니다. 데모를 위해 이 예제는 DataTemplate이 생성한 텍스트 블록의 텍스트 콘텐츠를 보여 주는 메시지 상자를 만듭니다.

// Getting the currently selected ListBoxItem
// Note that the ListBox must have
// IsSynchronizedWithCurrentItem set to True for this to work
ListBoxItem myListBoxItem =
    (ListBoxItem)(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.CurrentItem));

// Getting the ContentPresenter of myListBoxItem
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);

// Finding textBlock from the DataTemplate that is set on that ContentPresenter
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
TextBlock myTextBlock = (TextBlock)myDataTemplate.FindName("textBlock", myContentPresenter);

// Do something to the DataTemplate-generated TextBlock
MessageBox.Show("The text of the TextBlock of the selected list item: "
    + myTextBlock.Text);
' Getting the currently selected ListBoxItem
' Note that the ListBox must have
' IsSynchronizedWithCurrentItem set to True for this to work
Dim myListBoxItem As ListBoxItem = CType(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.CurrentItem), ListBoxItem)

' Getting the ContentPresenter of myListBoxItem
Dim myContentPresenter As ContentPresenter = FindVisualChild(Of ContentPresenter)(myListBoxItem)

' Finding textBlock from the DataTemplate that is set on that ContentPresenter
Dim myDataTemplate As DataTemplate = myContentPresenter.ContentTemplate
Dim myTextBlock As TextBlock = CType(myDataTemplate.FindName("textBlock", myContentPresenter), TextBlock)

' Do something to the DataTemplate-generated TextBlock
MessageBox.Show("The text of the TextBlock of the selected list item: " & myTextBlock.Text)

다음은 VisualTreeHelper 메서드를 사용하는 FindVisualChild의 구현입니다.

private childItem FindVisualChild<childItem>(DependencyObject obj)
    where childItem : DependencyObject
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(obj, i);
        if (child != null && child is childItem)
        {
            return (childItem)child;
        }
        else
        {
            childItem childOfChild = FindVisualChild<childItem>(child);
            if (childOfChild != null)
                return childOfChild;
        }
    }
    return null;
}
Private Function FindVisualChild(Of childItem As DependencyObject)(ByVal obj As DependencyObject) As childItem
    For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(obj) - 1
        Dim child As DependencyObject = VisualTreeHelper.GetChild(obj, i)
        If child IsNot Nothing AndAlso TypeOf child Is childItem Then
            Return CType(child, childItem)
        Else
            Dim childOfChild As childItem = FindVisualChild(Of childItem)(child)
            If childOfChild IsNot Nothing Then
                Return childOfChild
            End If
        End If
    Next i
    Return Nothing
End Function

참고 항목