tags:

views:

586

answers:

2

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!

A: 

It's not elegant, but it works. can anyone come up with a better solution? ("Next" functionality shown)

int index = 0;
foreach (TreeViewItem i in ParentItem.Items) {
    if (i.Equals(MyTreeView.SelectedItem)) {
        break;
    }
    index++;
}
(ParentItem.Items[index + 1] as TreeViewItem).IsSelected = true;
Pwninstein
+1  A: 

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 colleciton index.

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

Yordan Pavlov
Worked like a charm! Thanks!
Pwninstein