Files
docs-desktop/dotnet-desktop-guide/framework/wpf/data/how-to-find-datatemplate-generated-elements.md
Andy (Steve) De George e9fcf43083 Merge pull request #1135 from dotnet/adegeo-links
Correct .NET Framework links that pointed to old .NET 5 URLs
2021-08-11 12:04:34 -07:00

2.7 KiB

title, ms.date, dev_langs, helpviewer_keywords, ms.assetid
title ms.date dev_langs helpviewer_keywords ms.assetid
How to: Find DataTemplate-Generated Elements 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