wpf controls - Problem with traversing WPF element tree -
i have listbox
data bound collection of personcollection
class. next, have defined data template objects of type person
, consisted of dockpanel
contains textblock
person's name , button
remove person list. looks nice together.
the problem facing unable reach selected item (and delete it) in list box when click button defined in data template. here's handler of button:
private void removepersonbutton_click(object sender, routedeventargs e) { button clickedbutton = (button)e.source; dockpanel buttonpanel = (dockpanel)clickedbutton.parent; control control = (control)button.parent; }
the last created object control
null
, i.e. cannot progress further element tree, cannot reach list , selecteditem
. important thing note here cannot go getting selected item list calling it, because have more 1 list in window , lists implement same data template, i.e. share same event handler delete button.
i appreciate get. thanks.
if understand question correctly think you'll able person button's datacontext
private void removepersonbutton_click(object sender, routedeventargs e) { button clickedbutton = (button)e.source; person selecteditem = clickedbutton.datacontext person; if (selecteditem != null) { personcollection.remove(selecteditem); } }
another way find listbox in visualtree
private void removepersonbutton_click(object sender, routedeventargs e) { button clickedbutton = (button)e.source; listbox listboxparent = getvisualparent<listbox>(clickedbutton ); person selecteditem = listboxparent.selecteditem person; //... } public t getvisualparent<t>(object childobject) t : visual { dependencyobject child = childobject dependencyobject; while ((child != null) && !(child t)) { child = visualtreehelper.getparent(child); } return child t; }
Comments
Post a Comment