mirror of
https://github.com/Stone-Red-Code/docs-desktop.git
synced 2026-09-04 09:06:04 +02:00
42 lines
2.7 KiB
Markdown
42 lines
2.7 KiB
Markdown
---
|
|
title: "How to: Find DataTemplate-Generated Elements"
|
|
ms.date: "03/30/2017"
|
|
dev_langs:
|
|
- "csharp"
|
|
- "vb"
|
|
helpviewer_keywords:
|
|
- "finding DataTemplate elements [WPF]"
|
|
- "DataTemplate [WPF]"
|
|
ms.assetid: bfcd564e-5e9e-451e-8641-a9b5c3cfac90
|
|
---
|
|
# How to: Find DataTemplate-Generated Elements
|
|
This example shows how to find elements that are generated by a <xref:System.Windows.DataTemplate>.
|
|
|
|
## Example
|
|
In this example, there is a <xref:System.Windows.Controls.ListBox> that is bound to some XML data:
|
|
|
|
[!code-xaml[FindGeneratedItems#LB](~/samples/snippets/csharp/VS_Snippets_Wpf/FindGeneratedItems/CSharp/Window1.xaml#lb)]
|
|
|
|
The <xref:System.Windows.Controls.ListBox> uses the following <xref:System.Windows.DataTemplate>:
|
|
|
|
[!code-xaml[FindGeneratedItems#DT](~/samples/snippets/csharp/VS_Snippets_Wpf/FindGeneratedItems/CSharp/Window1.xaml#dt)]
|
|
|
|
If you want to retrieve the <xref:System.Windows.Controls.TextBlock> element generated by the <xref:System.Windows.DataTemplate> of a certain <xref:System.Windows.Controls.ListBoxItem>, you need to get the <xref:System.Windows.Controls.ListBoxItem>, find the <xref:System.Windows.Controls.ContentPresenter> within that <xref:System.Windows.Controls.ListBoxItem>, and then call <xref:System.Windows.FrameworkTemplate.FindName%2A> on the <xref:System.Windows.DataTemplate> that is set on that <xref:System.Windows.Controls.ContentPresenter>. The following example shows how to perform those steps. For demonstration purposes, this example creates a message box that shows the text content of the <xref:System.Windows.DataTemplate>-generated text block.
|
|
|
|
[!code-csharp[FindGeneratedItems#DTFindElement](~/samples/snippets/csharp/VS_Snippets_Wpf/FindGeneratedItems/CSharp/Window1.xaml.cs#dtfindelement)]
|
|
[!code-vb[FindGeneratedItems#DTFindElement](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FindGeneratedItems/VisualBasic/Window1.xaml.vb#dtfindelement)]
|
|
|
|
The following is the implementation of `FindVisualChild`, which uses the <xref:System.Windows.Media.VisualTreeHelper> methods:
|
|
|
|
[!code-csharp[FindGeneratedItems#FVC](~/samples/snippets/csharp/VS_Snippets_Wpf/FindGeneratedItems/CSharp/Window1.xaml.cs#fvc)]
|
|
[!code-vb[FindGeneratedItems#FVC](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FindGeneratedItems/VisualBasic/Window1.xaml.vb#fvc)]
|
|
|
|
## See also
|
|
|
|
- [How to: Find ControlTemplate-Generated Elements](../controls/how-to-find-controltemplate-generated-elements.md)
|
|
- [Data Binding Overview](data-binding-overview.md)
|
|
- [How-to Topics](data-binding-how-to-topics.md)
|
|
- [Styling and Templating](../controls/styles-templates-overview.md)
|
|
- [WPF XAML Namescopes](../advanced/wpf-xaml-namescopes.md)
|
|
- [Trees in WPF](../advanced/trees-in-wpf.md)
|