Getting the SelectedIndex of a child node in a TreeView

Johnston picture Johnston · Jun 18, 2011 · Viewed 12.1k times · Source

I am currently working on a wpf project in C#.

I have a treeview created that has parent nodes with childen nodes inside of it.

I was wondering if there was a way to get the index of the child node the user clicked on. (Simmilar to ".SelectedIndex" when using comboboxes)

I have tried Various ways such as:

int val =TreeView.SelectedItemProperty.GlobalIndex;

and

fileInput.IndexOf(treeView1.SelectedItem);

But they dont seem to work.

Any suggestions or comments are greatly appreciated.

Thanks

Answer

Amir Ismail picture Amir Ismail · Jun 18, 2011

may you have to loop over tree nodes to get the index of SelectedItem. you can do that using OnItemSelected event.for ex.

Int32 selectedNodeIndex=-1;
private void TreeView1_OnItemSelected(Object sender,RoutedEventArgs e)
{
      Int32 index=0;
      foreach(var _item in TreeView1.Items)
      {
         if(_item==TreeView1.SelectedItem)
         {
                selectedNodeIndex = index;
                break;
         }
          index++;
      }    
}