private TreeViewItem FindNextFocusableItem(bool recurse)
{
// Look for the next item in the children of this item (if allowed)
if (recurse && IsExpanded && HasItems)
{
TreeViewItem item = ItemContainerGenerator.ContainerFromIndex(0) as TreeViewItem;
if (item != null)
{
return item.IsEnabled ?
item :
item.FindNextFocusableItem(false);
}
}
// Look for the next item in the siblings of this item
ItemsControl parent = ParentItemsControl;
if (parent != null)
{
// Get the index of this item relative to its siblings
TreeViewItem item = null;
int index = parent.ItemContainerGenerator.IndexFromContainer(this);
int count = parent.Items.Count;
// Check for any siblings below this item
while (index++ < count)
{
item = parent.ItemContainerGenerator.ContainerFromIndex(index) as TreeViewItem;
if (item != null && item.IsEnabled)
{
return item;
}
}
// If nothing else was found, try to find the next sibling below
// the parent of this item
TreeViewItem parentItem = ParentTreeViewItem;
if (parentItem != null)
{
return parentItem.FindNextFocusableItem(false);
}
}
return null;
}