Skip to content

Instantly share code, notes, and snippets.

@chrisnicola
Created December 26, 2010 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisnicola/755546 to your computer and use it in GitHub Desktop.
Save chrisnicola/755546 to your computer and use it in GitHub Desktop.
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); }
}
}
@ashleyabraham
Copy link

Is there a XAML example that goes along with this MyVirtualizingStackPanel code, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment