方法 : DataTemplate によって生成された要素を検索する

更新 : 2007 年 11 月

この例では、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);

次に示すのは、FindVisualChild の実装です。この実装は、VisualTreeHelper メソッドを使用しています。

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;
}

サンプル全体については、「テンプレートによって生成された要素の検索のサンプル」を参照してください。

参照

処理手順

方法 : ControlTemplate によって生成された要素を検索する

概念

データ バインディングの概要

スタイルとテンプレート

WPF 名前スコープ

WPF のツリー

その他の技術情報

データ バインディングのサンプル

データ バインディングに関する「方法」トピック