HOW TO:尋找 DataTemplate 產生的項目
更新:2007 年 11 月
這個範例顯示如何尋找 DataTemplate 產生的項目。
範例
這個範例中有一個 ListBox 已繫結至某些 XML 資料:
<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>
如果您想擷取由特定 ListBoxItem 的 DataTemplate 所產生的 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;
}
如需完整範例,請參閱尋找範本產生的項目範例。
請參閱
工作
HOW TO:尋找 ControlTemplate 產生的項目