Skip to content

Latest commit

 

History

History
44 lines (32 loc) · 2.8 KB

how-to-find-datatemplate-generated-elements.md

File metadata and controls

44 lines (32 loc) · 2.8 KB
title description ms.date dev_langs helpviewer_keywords ms.assetid
How to: Find DataTemplate-Generated Elements
Learn how to find elements that are generated by a DataTemplate with several provided code examples.
03/30/2017
csharp
vb
finding DataTemplate elements [WPF]
DataTemplate [WPF]
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-xamlFindGeneratedItems#LB]

The xref:System.Windows.Controls.ListBox uses the following xref:System.Windows.DataTemplate:

[!code-xamlFindGeneratedItems#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-csharpFindGeneratedItems#DTFindElement] [!code-vbFindGeneratedItems#DTFindElement]

The following is the implementation of FindVisualChild, which uses the xref:System.Windows.Media.VisualTreeHelper methods:

[!code-csharpFindGeneratedItems#FVC] [!code-vbFindGeneratedItems#FVC]

See also