using System.Collections.Generic; using System.Windows.Controls; using System.Windows.Media; namespace System.Windows.Forms { public partial class TreeView { private static class SelectItemHelper { public static void Select(CustomControls.TreeView tree, TreeNode newNode) { if (!tree.IsLoaded) return; if (newNode == null) return; var nodeDynasty = new List { newNode }; var parent = newNode.Parent; while (parent != null) { nodeDynasty.Insert(0, parent); parent = parent.Parent; } var currentParent = tree as ItemsControl; foreach (var node in nodeDynasty) { // first try the easy way var newParent = currentParent.ItemContainerGenerator.ContainerFromItem(node) as TreeViewItem; if (newParent == null) { // if this failed, it's probably because of virtualization, and we will have to do it the hard way. // see also the question at http://stackoverflow.com/q/183636/46635 var itemsPresenter = (ItemsPresenter)currentParent.Template.FindName("ItemsHost", currentParent); if (itemsPresenter == null) return; var virtualizingPanel = (VirtualizingPanel)VisualTreeHelper.GetChild(itemsPresenter, 0); var index = currentParent.Items.IndexOf(node); if (index < 0) return; virtualizingPanel.BringIndexIntoViewPublic(index); newParent = currentParent.ItemContainerGenerator.ContainerFromIndex(index) as TreeViewItem; } if (newParent == null) return; if (node == newNode) { newParent.IsSelected = true; newParent.BringIntoView(); break; } newParent.IsExpanded = true; currentParent = newParent; } } } } }