简体   繁体   中英

How to get User Control in listbox data template item

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM