Saturday, 15 August 2015

c# - Get parent TreeViewItem of a selected node in WPF -



c# - Get parent TreeViewItem of a selected node in WPF -

i want parent of node selected treeviewitem

i have person class 2 fields. name(string) , children(list of string)

this xaml code

<grid x:name="gridview" margin="10"> <treeview name="treeview1" treeviewitem.selected="treeviewitem_onitemselected" itemssource="{binding}"> <treeview.itemcontainerstyle> <style targettype="{x:type treeviewitem}"> <setter property="isselected" value="{binding isselected, source=check, mode=twoway}" /> </style> </treeview.itemcontainerstyle> <treeview.resources> <hierarchicaldatatemplate datatype="{x:type loc:person}" itemssource="{binding children}" > <textblock text="{binding name}" /> </hierarchicaldatatemplate> </treeview.resources> </treeview> </grid>

this code behind. set item source list of person objects.

void set() { if (treeview1.items.indexof(treeview1.selecteditem) != -1) { //is parent //returns -1 children person selected = (person)treeview1.selecteditem; int index = search(selected); treeviewitem parent = treeview1.tag treeviewitem; setselected(parent,index); } else { //is kid treeviewitem kid = treeview1.tag treeviewitem; //returns selected node treeviewitem parent = child.parent treeviewitem; //returns null } } private void treeviewitem_onitemselected(object sender, routedeventargs e) { treeview1.tag = e.originalsource; int ind = 0; foreach (var _item in treeview1.items) { if (_item == treeview1.selecteditem) { selectedindex = ind; break; } ind++; } }

in else part, child.parent returns null. tried other methods none of them homecoming treeviewitem instead homecoming dependencyobject or itemscontrol.

i tried containerfromitem method works direct children(parent) , not children of parent.

please help

itemssource typically collection of dependencyobjects can bind to. doesn't reflect info ui. looking itemcontainer of each item part of wpf ui.

in cases can access uielement without problem. in experience ui gets complicated styles, templates , hierarchical items, uielements hard find.

i suggest next way:

implement parent property in viewmodel (person class) type of person , initialize in constructor of person, can both parent person , parent treeviewitem this:

var parentperson = (treeview1.selecteditem person).parent; var parentnode = treeview1.itemcontainergenerator.containerfromitem(parentperson);

c# wpf treeview wpf-controls treeviewitem

No comments:

Post a Comment