1

我有一个列表框:

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

使用以下数据模板:

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

如何检索数据模板生成的 UiElement?

4

1 回答 1

4

如果要检索某个 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);
于 2013-10-09T10:15:21.827 回答