我的变体至少适用于 4 级树。
如果光标遇到最后一个 treeviewitem,它将在开始时进行。如果您在第一个节点按 Previous,您将留在原地。
// Button Back
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (treeViewStruct.Items.Count < 1) return;
if (Currentitem == null)
{
((TreeViewItem)treeViewStruct.Items[0]).IsSelected = true;
return;
}
TreeViewItem item = FindPreviousItem(Currentitem);
if (item == null)
((TreeViewItem)treeViewStruct.Items[0]).IsSelected = true;
else item.IsSelected = true;
}
/// <summary>
/// Get Previous Node
/// </summary>
/// <param name="item">Current selected node</param>
/// <returns></returns>
private static TreeViewItem FindPreviousItem(TreeViewItem item)
{
TreeViewItem foundedItem = null;
var parentItem = (item.Parent as TreeViewItem);
if (parentItem != null)
{
int index = parentItem.Items.IndexOf(item);
if (index > 0 && index < parentItem.Items.Count)
{
return FindLastChildren((TreeViewItem)parentItem.Items[index - 1]);
}
else if (index == 0)
return parentItem;
}
else return item;
return foundedItem;
}
private static TreeViewItem FindLastChildren(TreeViewItem parent)
{
if (parent.Items.Count > 0)
{
return FindLastChildren((TreeViewItem)parent.Items.Last());
}
else return parent;
}
// вперед
private void Button_Click_2(object sender, RoutedEventArgs e)
{
if (treeViewStruct.Items.Count < 1) return;
if (Currentitem == null)
{
((TreeViewItem)treeViewStruct.Items[0]).IsSelected = true;
return;
}
TreeViewItem item = FindNextItem(Currentitem);
if (item == null)
((TreeViewItem)treeViewStruct.Items[0]).IsSelected = true;
else item.IsSelected = true;
}
/// <summary>
/// Get Next Node
/// </summary>
/// <param name="item">Current selected node</param>
/// <returns></returns>
private static TreeViewItem FindNextItem(TreeViewItem item)
{
TreeViewItem foundedItem = null;
if (item.Items.Count < 1)
{
var parentItem = (item.Parent as TreeViewItem);
if (parentItem != null)
{
int index = parentItem.Items.IndexOf(item);
if (index > 0 && index < parentItem.Items.Count - 1)
{
return (TreeViewItem)parentItem.Items[index + 1];
}
else if (index == parentItem.Items.Count - 1)
{
return FindFirstNextParent(parentItem);
}
}
else return item;
}
return (TreeViewItem)item.Items[0];
}
private static TreeViewItem FindFirstNextParent(TreeViewItem parent)
{
var parentParent = ((TreeViewItem)parent).Parent;
if (parentParent is TreeViewItem)
{
int pindex = ((TreeViewItem)parentParent).Items.IndexOf(parent);
if ((pindex + 1) < ((TreeViewItem)parentParent).Items.Count)
return ((TreeViewItem)((TreeViewItem)parentParent).Items[pindex + 1]);
else
{
return FindFirstNextParent(((TreeViewItem)((TreeViewItem)parent).Parent));
}
}
return parent;
}