--- title: "How to: Find a TreeViewItem in a TreeView" ms.date: "03/30/2017" dev_langs: - "csharp" - "vb" helpviewer_keywords: - "TreeView control [WPF], finding a TreeViewItem" - "TreeViewItem [WPF], finding" ms.assetid: 72ecd40c-3939-4e01-b617-5e9daa6074d9 --- # How to: Find a TreeViewItem in a TreeView The control provides a convenient way to display hierarchical data. If your is bound to a data source, the property provides a convenient way for you to quickly retrieve the selected data object. It is typically best to work with the underlying data object, but sometimes you may need to programmatically manipulate the data's containing . For example, you may need to programmatically expand the , or select a different item in the . To find a that contains a specific data object, you must traverse each level of the . The items in a can also be virtualized to improve performance. In the case where items might be virtualized, you also must realize a to check whether it contains the data object. ## Example ## Description The following example searches a for a specific object and returns the object's containing . The example ensures that each is instantiated so that its child items can be searched. This example also works if the does not use virtualized items. > [!NOTE] > The following example works for any , regardless of the underlying data model, and searches every until the object is found. Another technique that has better performance is to search the data model for the specified object, keep track of its location within the data hierarchy, and then find the corresponding in the . However, the technique that has better performance requires knowledge of the data model and cannot be generalized for any given . ## Code [!code-csharp[TreeViewFindTVI#1](~/samples/snippets/csharp/VS_Snippets_Wpf/TreeViewFindTVI/CSharp/MainWindow.xaml.cs#1)] [!code-vb[TreeViewFindTVI#1](~/samples/snippets/visualbasic/VS_Snippets_Wpf/TreeViewFindTVI/VisualBasic/MainWindow.xaml.vb#1)] The previous code relies on a custom that exposes a method named `BringIntoView`. The following code defines the custom . [!code-csharp[TreeViewFindTVI#2](~/samples/snippets/csharp/VS_Snippets_Wpf/TreeViewFindTVI/CSharp/MainWindow.xaml.cs#2)] [!code-vb[TreeViewFindTVI#2](~/samples/snippets/visualbasic/VS_Snippets_Wpf/TreeViewFindTVI/VisualBasic/MainWindow.xaml.vb#2)] The following XAML shows how to create a that uses the custom . [!code-xaml[TreeViewFindTVI#3](~/samples/snippets/csharp/VS_Snippets_Wpf/TreeViewFindTVI/CSharp/MainWindow.xaml#3)] ## See also - [Improve the Performance of a TreeView](how-to-improve-the-performance-of-a-treeview.md)