sajid raja

sajid raja

  • NA
  • 66
  • 46.6k

Count All items inside a listbox in windowsphone 8

Jun 30 2013 12:46 PM
Hello
I am creating a windows app with a listbox. i have placed a textbox and a check box inside Listview that are being generated dynamically using C#. I want to Un check all check boxes on button click event. My XAML code is .

 <ListBox Name="lstcontacts" ItemsSource="{Binding}" Margin="10,52,10,113"  SelectionMode="Multiple" Foreground="#FF333333" >
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <CheckBox x:Name="contactChk" Tag="{Binding}" IsChecked="true" IsEnabled="True" Foreground="Black" Background="Black" BorderBrush="Black" Checked="chbox_checked" />
                           
                            <TextBlock Name="txtResults" Text="{Binding Path=DisplayName, Mode=OneWay}"  />
                           
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

and my C# code is as follows.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Data;
using Microsoft.Phone.UserData;
using Microsoft.Phone.Tasks;
using System.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;




namespace MyPhoneBackup
{
    public partial class CreateContactBackups : PhoneApplicationPage
    {
        //AddressChooserTask addressChooserTask;
        //PhoneNumberChooserTask addressChooserTask;


        public CreateContactBackups()
        {
            InitializeComponent();
           
            Contacts cContacts = new Contacts();
            cContacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(ContactsSearch);
            cContacts.SearchAsync(String.Empty, FilterKind.DisplayName, null);






            /* addressChooserTask = new PhoneNumberChooserTask();
            addressChooserTask.Completed += new EventHandler<PhoneNumberResult>(addressChooserTask_Completed); 
            //addressChooserTask.Completed += new EventHandler<AddressResult>(addressChooserTask_Completed); */




        }


        /*
         void addressChooserTask_Completed(object sender, PhoneNumberResult e)
         {
             if (e.TaskResult == TaskResult.OK)
             {
                 txtDisplay.Text = "The address for " + e.DisplayName + " is " + e.PhoneNumber;
             }
         }*/




        private void Button_Click_2(object sender, RoutedEventArgs e)
        {




            /*try
            {
                addressChooserTask.Show();
            }
            catch (System.InvalidOperationException ex)
            {
            }*/


        }




        void ContactsSearch(object sender, ContactsSearchEventArgs e)
        {
            try
            {
                lstcontacts.DataContext = e.Results;
            }
            catch (System.Exception)
            {
                txtResults.Text = "No Results Available";
            }
            if (lstcontacts.Items.Any())
            {
                txtResults.Text = "Below is the List of Contacts";
            }
            else
            {
                txtResults.Text = "No Results Available";
            }
        }


        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
                       //CheckBox contactChk = lstcontacts.SelectedItem as CheckBox;
            SearchVisualTree(this.lstcontacts);


             int count22 = lstcontacts.Items.Count;
             for (int i = 0; i <= count22; i++ )
             {


                 ListBoxItem item = this.lstcontacts.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
                 CheckBox contactChk = FindFirstElementInVisualTree<CheckBox>(item);
                 contactChk.IsChecked = false;
             }
        }


        private void SearchVisualTree(DependencyObject targetElement)
        {
            var count = VisualTreeHelper.GetChildrenCount(targetElement);
            if (count == 0)
                return;


            for (int i = 0; i < count; i++)
            {
                var child = VisualTreeHelper.GetChild(targetElement, i);
                if (child is TextBlock)
                {
                    TextBlock myItems = (TextBlock)child;
                    if (myItems.Text == "Item2")                    {
                        myItems.Foreground = new SolidColorBrush(Colors.Green);
                        return;
                    }
                }
                else
                {
                    SearchVisualTree(child);
               }
            }


        }


        private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
        {
            var count = VisualTreeHelper.GetChildrenCount(parentElement);
            if (count == 0)
                return null;
            for (int i = 0; i <= count; i++)
            {
                var child = 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;
        }


        public void chbox_checked(object sender, RoutedEventArgs e) {
           




        }
   
    }


   


}





If i remove variable int count22 and loop below this and replace index i in ContainerFromIndex(i) with a  digit then this program works fine other wise it shown following exception "An exception of type 'System.InvalidOperationException' occurred in System.Windows.ni.dll but was not handled in user code" at 
 var count = VisualTreeHelper.GetChildrenCount(parentElement); 

in FindFirstElementInVisualTree method. If any one can help me . Please help.