.net – How to select the Next/Previous TreeViewItem in a TreeView

.nettreeviewtreeviewitemwpf

I have First/Last/Previous/Next buttons that change the selected child node of a TreeViewItem. Setting the First and Last node as selected is not a problem. For example, to select the last child node:

TreeViewItem selectedItem = (myTreeView.SelectedItem as TreeViewItem);
TreeViewItem ParentItem = (selectedItem.Parent as TreeViewItem);
(ParentItem.Items[ParentItem.Items.Count - 1] as TreeViewItem).IsSelected = true;

What would be the easiest/most elegant way to set the Previous/Next item as being selected?

Thanks!

Best Solution

You could replace the for loop with a IndexOf call.

int index = ParentItem.Items.IndexOf(MyTreeView.SelectedItem)

And of course it will be good to check if index + 1 is a valid collection index.

And for the previous sibling it will be index - 1.