0

I am trying to get added user control in a list box, but couldn't find proper way to get it.

I am using below for finding user controls in binded listbox, but out of 10 items it could not find 3 or 4.

private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
        {
            var count = System.Windows.Media.VisualTreeHelper.GetChildrenCount(parentElement);
            if (count == 0)
                return null;

            for (int i = 0; i < count; i++)
            {
                var child = System.Windows.Media.VisualTreeHelper.GetChild(parentElement, i);

                if (child != null && child is T)
                    return (T)child;
                else
                {
                    var result = FindFirstElementInVisualTree<T>(child);
                    if (result != null)
                        return result;

                }
            }
            return null;
        }

Code for button click to find user control.

private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (!downloadClicked)
            {
                downloadClicked = true;
                SuraWithProgressBar prg = null;
                ListBoxItem item = null;
                for (int rowIndex = 0; rowIndex < lsbQuranData.Items.Count; rowIndex++)
                {
                    item = this.lsbQuranData.ItemContainerGenerator.ContainerFromIndex(rowIndex) as ListBoxItem;
                    if (item != null)
                    {
                        prg = FindFirstElementInVisualTree<SuraWithProgressBar>(item);
                        if (prg != null)
                        {
                            //Do Somthing
                            prg.addButtonClickInterface(this);
                        }
                    }
                }
            }
            else
                MessageBox.Show("Please wait, downloading...");
        }

As I mentioned out of 10, It cannot find 3-4 items. I am looking for proper way to find my user control inside listbox.

Thanks!

ARH
  • 1,566
  • 3
  • 25
  • 56
  • After alot of headache i find solution here (http://stackoverflow.com/questions/9897141/wp7-visualtreehelper-to-loop-through-all-listbox-items) and (http://msdn.microsoft.com/en-us/library/windows/apps/jj709920.aspx) – ARH Jan 23 '14 at 19:03

1 Answers1

0

After a lot of headache I find out the solution in two below links:

WP7 - VisualTreeHelper to loop through all ListBox Items

http://msdn.microsoft.com/en-us/library/windows/apps/jj709920.aspx

Add template to your listbox and change SerializeStackPanel to StackPanel and the problem is solved. Please make sure to add this to ItemTemplate section.

Community
  • 1
  • 1
ARH
  • 1,566
  • 3
  • 25
  • 56