so walk the descendents and find the child. The Tree template has not named the ItemsPresenter, (ItemsPresenter)("ItemsHost", container) regenerate the visuals because they may have been virtualized away. expanded we still need to do this step in order to virtualizing case even if the item is marked Try to generate the ItemsPresenter and the ItemsPanel. If (container is TreeViewItem & !((TreeViewItem)container).IsExpanded)Ĭontainer.SetValue(TreeViewItem.IsExpandedProperty, true) Private TreeViewItem GetTreeViewItem(ItemsControl container, object item) / The TreeViewItem that contains the specified item. This can be a TreeView or a TreeViewItem. / Recursively search for an item in this subtree. However, the technique that has better performance requires knowledge of the data model and cannot be generalized for any given TreeView. 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 TreeViewItem in the TreeView. The following example works for any TreeView, regardless of the underlying data model, and searches every TreeViewItem until the object is found. This example also works if the TreeView does not use virtualized items. The example ensures that each TreeViewItem is instantiated so that its child items can be searched. The following example searches a TreeView for a specific object and returns the object's containing TreeViewItem. In the case where items might be virtualized, you also must realize a TreeViewItem to check whether it contains the data object. The items in a TreeView can also be virtualized to improve performance. To find a TreeViewItem that contains a specific data object, you must traverse each level of the TreeView. For example, you may need to programmatically expand the TreeViewItem, or select a different item in the TreeView. It is typically best to work with the underlying data object, but sometimes you may need to programmatically manipulate the data's containing TreeViewItem. If your TreeView is bound to a data source, the SelectedItem property provides a convenient way for you to quickly retrieve the selected data object. The TreeView control provides a convenient way to display hierarchical data.