public
Created

  • Download Gist
TreeViewItemFinder.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
using System;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
 
namespace Presentation.Helpers {
 
public static class TreeViewitemFinder {
public static TreeViewItem BringTreeViewItemIntoView(this TreeView treeView, TreeViewItemModel item) {
if (item == null) return null;
ItemsControl parentContainer = (ItemsControl) treeView.BringTreeViewItemIntoView(item.Parent) ?? treeView;
return parentContainer.BringItemIntoView(item);
}
 
private static TreeViewItem BringItemIntoView(this ItemsControl container, object item) {
var vsp = container.FindVisualChild<MyVirtualizingStackPanel>();
if (vsp == null) {
var treeViewItem = (TreeViewItem) container.ItemContainerGenerator.ContainerFromItem(item);
treeViewItem.BringIntoView();
return treeViewItem;
}
//Use exposed BringIntoView method to render each of the items in order
for (int i = 0; i < container.Items.Count; i++) {
vsp.Dispatcher.Invoke(DispatcherPriority.ContextIdle, (Action<int>) vsp.BringIntoView, i);
var nextitem = (TreeViewItem) container.ItemContainerGenerator.ContainerFromIndex(i);
if (nextitem.DataContext == item) {
nextitem.Dispatcher.Invoke(DispatcherPriority.ContextIdle, (Action) nextitem.BringIntoView);
return nextitem;
}
}
return null;
}
 
private static T FindVisualChild<T>(this Visual visual) where T : Visual {
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++) {
var child = (Visual) VisualTreeHelper.GetChild(visual, i);
if (child != null) {
var correctlyTyped = child as T;
if (correctlyTyped != null)
return correctlyTyped;
var descendent = FindVisualChild<T>(child);
if (descendent != null)
return descendent;
}
}
return null;
}
}
 
public class MyVirtualizingStackPanel : VirtualizingStackPanel {
public void BringIntoView(int index) { BringIndexIntoView(index); }
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.