wpf - Access another control in a DataTemplate in code behind -
i have datatemplate containing multiple controls. 1 of controls button needs access other controls in datatemplate
<datatemplate> <stackpanel> <combobox x:name="optionscombo" > <comboboxitem content="option1" /> <comboboxitem content="option2" /> <comboboxitem content="option3" /> </combobox> <button name="dosomethingbutton" margin="10" click="dosomethingbutton_click">do something</button> </stackpanel> </datatemplate> in code behind button click event, if attempt access combobox name this:
private void dosomethingbutton_click(object sender, routedeventargs e) { comboboxitem myitem = (comboboxitem)optionscombo.selecteditem; } i error: "the name 'optionscombo' not exist in current context"
so, how access other controls in datatemplate button click event?
you can't access that, because there's no code generation datatemplates, i.e. optionscombo combobox not exist in compilation time, hence error. manipulate in code behind, need use visualtreehelper, it's described on net. parent panel of sender, find combobox name, , cast it's proper type. there have it!
Comments
Post a Comment