Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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);
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); }

This comment has been minimized.

Copy link

commented Jun 10, 2016

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
You can’t perform that action at this time.