views:

743

answers:

2

hi, i made a listbox that generates dynamic controls such as dropdowns & datepicker. i wanted to retrieve the data within the rows. Normally, in windows forms we commonly index the ...Items[i].FindControl("ControlID") method. How do you do about in XAML?

I need to retrieve the changes upon clicking a button.

btw, here's a simple view of my xaml:

<ListBox>
    <stackpanel>
           <TextBlock />
           <stackpanel>
                <grid>
                  <combobox />
                  <combobox/>
                  <datepicker />
                </grid>
          </stackpanel>
    </stackpanel>
</ListBox>

Thank you so much!

+1  A: 

The most straightforward way would be to set a two-way binding on of your controls to objects and then the objects will tell you what the values were set to.

Also you can go through your tree by going through the Content properties of the objects until you get to the leaf objects.

Alternatively, you can use the Selected item and call the VisualTreeHelper's GetChild Method until you're at the leaf objects.

Correl
A: 
    private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
  FrameworkElement selectedItem = (sender as ListBox).SelectedItem as FrameworkElement;
  List<FrameworkElement> children = new List<FrameworkElement>();
  children = GetChildren(selectedItem, ref children);
 }

 private List<FrameworkElement> GetChildren(FrameworkElement element, ref List<FrameworkElement> list)
 {
  int count = VisualTreeHelper.GetChildrenCount(element);

  for (int i = 0; i < count; i++)
  {
   FrameworkElement child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;

   if(child != null)
   {
    list.Add(child);
    GetChildren(child, ref list);
   }
  }

  return list;
 }

This returns all the FrameworkElements (including paths, borders etc). You can easily extend it and call the GetChildren method recursively only if the child is of certain type (ComboBox, StackPanel etc)

Kiril