int GetDepth(TreeViewItem item) { FrameworkElement elem = item; FrameworkElement parent = UtilMethods.FindAncestor <FrameworkElement>(elem); while (parent != null) { parent = UtilMethods.FindAncestor <FrameworkElement>(elem); var tvi = parent as TreeViewItem; if (null != tvi) { return(GetDepth(tvi) + 1); } elem = parent; } return(0); }