WPF Accessing Items inside Listbox which has a UserControl as ItemTemplate

Posted by Turker on Stack Overflow See other posts from Stack Overflow or by Turker
Published on 2010-05-29T13:42:54Z Indexed on 2010/05/29 13:52 UTC
Read the original article Hit count: 315

Filed under:
|
|
|
  • I have Window that has a ListBox
  • ListBox(MyListBox) has a DataTable for its DataContext
  • ListBox's ItemSource is : {Binding}
  • Listbox has a UserControl(MyUserControl) as DataTemplate
  • UserControl has RadioButtons and TextBoxes (At first They're filled with values from DataTable and then user can change them)
  • Window has one Submit Button

What I want to do is, when user clicks the submit button

  • For each ListBox Item, get the values form UserControl's TextBoxes and RadioButtons.

I was using that method for this job :

foreach(var element in MyListBox.Items)
{ 
  var border = MyListBox.ItemContainerGenerator.ContainerFromItem(element)as FrameworkElement;
  MyUserControl currentControl = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(myBorder,0) as Border,0)as ContentPresenter,0)as MyUserControl;
  //And use currentControl
}

I realised nothing when using 3-5 items in Listbox. But when I used much more items, I saw that "var border" gets "null" after some elements looped in foreach function.

I found the reason here : http://stackoverflow.com/questions/1675926/listview-itemcontainergenerator-containerfromitemitem-return-null-after-20-item

So what can I do now? I want to access all items and get their values sitting on user controls.

Thanks

© Stack Overflow or respective owner

Related posts about wpf

Related posts about listbox