Getting the SelectedIndex of a child node in a TreeView

痴心易碎 提交于 2019-12-07 18:32:51

问题


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


回答1:


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++;
      }    
}



回答2:


This post discusses exactly what you need I think. About handling the SelectedNodeChanged event and also a custom piece of code for an event that fires when the currently selected node is clicked...because then the SelectedNodeChanged doesn't fire (the selected node doesn't change actually). Good luck!



来源:https://stackoverflow.com/questions/6398878/getting-the-selectedindex-of-a-child-node-in-a-treeview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!