Search code examples
wpfwindows-phone-8.1windows-phone

Cant access all children of element?


So i am adding some elements to a map control like this

  foreach (var res in results)
            {
                if (res.geometry.location != null)
                {
                    var pushpin = new Image();
                    pushpin.Name = "a";
                     BasicGeoposition bs = new BasicGeoposition { Latitude = res.geometry.location.lat, Longitude = res.geometry.location.lng };
                    pushpin.Source = new BitmapImage(uri);
                    pushpin.Height = 50;
                    pushpin.Width = 50;
                    myMap.Children.Add(pushpin);
                    MapControl.SetLocation(pushpin, new Geopoint(bs));


                }

            }

Now i want to remove elements names "a" form the control and i am using following code

    int c = myMap.Children.Count;
            for (int i = 0; i < c; i++)
            {

                if(myMap.Children.ElementAt(i) is Image)
                {
                    var z = myMap.Children.ElementAt(i) as Image;
                    if(z.Name.Equals("a"))
                        {
                        myMap.Children.Remove(myMap.Children.ElementAt(i));
                    }


                }


            }

But always some elements are not getting removed ,for example the count of children is coming 21,but the loop is looping only 10 time. How can i solve this problem?


Solution

  • try it with looping backwards so you dont mess up your collection during the loop.

    int c = myMap.Children.Count - 1;
    for (int i = c; i >= 0; i--)
    {
        if (myMap.Children.ElementAt(i) is Image)
        {
            var z = myMap.Children.ElementAt(i) as Image;
            if(z.Name.Equals("a"))
            {
                myMap.Children.Remove(myMap.Children.ElementAt(i));
            }
        }
    }