c# - WPF - Treeview selected item index -


i have treeview panel. in panel, there several child nodes. of them header.

the way create treeview:

treeviewpanel.items.add(art); art.items.add(prt);  if statement....  treeviewitem cldhdr = new treeviewitem() { header = "childnodes:" }; prt.items.add(cldhdr); treeviewitem cld = new treeviewitem() ....... ........ ..... cldhdr.items.add(cld); 

treeview:

node1   childnodes:           (this header only.  appears if child node exists)    childnode1    childnode2    childnode3  node2 node3   childnodes:               childnode1    childnode2    childnode3  node4 node5 

in treeview there images in front of nodes. it's code driven treeview. in xaml part have only:

<treeview x:name="treeviewpanel" selecteditemchanged="treeviewpanel_selecteditemchanged" >                     </treeview> 

what want when click on of treeview items, need index number.

my code is:

private void treeviewpanel_selecteditemchanged(object sender, routedpropertychangedeventargs<object> e)     {   int index = 0;  itemscontrol parent = itemscontrol.itemscontrolfromitemcontainer(prt);   foreach (var _item in parent.items)         {               if (_item == treeviewpanel.selecteditem)             {                 selectednodeindex = index;                 messagebox.show(selectednodeindex.tostring());                 break;             }             index++;         }  }  

with code above, can index of node1,node2,node3, node4 , node5 0,1,2,3,4

what want index numbers as:

node1  = 0 childnode1 = 1       (skipping header) childnode2 = 2 childnode3 = 3 node2  = 4 .... .... .... 

what missing?

here solution, first of "mytreeviewitem"

public class mytreeviewitem :treeviewitem {     private int _index;     public int index     {         { return _index; }         set { _index = value; }     }      public mytreeviewitem() : base()      {      } } 

and usage;

            mytreeviewitem art = new mytreeviewitem();             art.header = "node1";             art.index = 1;                mytreeviewitem prt = new mytreeviewitem();             prt.header = "child1";             prt.index = 2;               art.items.add(prt);               treeviewpanel.items.add(art);  

and event;

  private void treeviewpanel_selecteditemchanged(object sender,   routedpropertychangedeventargs<object> e)         {             mytreeviewitem selecteditem = e.newvalue mytreeviewitem;             if (selecteditem != null)              {                 messagebox.show("" + selecteditem.index);              }         } 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -