Find DataTemplate-Generated Elements

How to: Find DataTemplate-Generated Elements

 

This example shows how to find elements that are generated by a DataTemplate.

Example

In this example, there is a ListBox that is bound to some XML data:

The ListBox uses the following DataTemplate:

If you want to retrieve the TextBlock element generated by the DataTemplate of a certain ListBoxItem, you need to get the ListBoxItem, find the ContentPresenter within that ListBoxItem, and then call FindName on the DataTemplate that is set on that 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 DataTemplate-generated text block.

The following is the implementation of FindVisualChild, which uses the VisualTreeHelper methods:

Show:
© 2016 Microsoft