无法访问所有 children 元素?

Cant access all children of element?

所以我要像这样向地图控件添加一些元素

  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));


                }

            }

现在我想从控件中删除元素名称 "a",我正在使用以下代码

    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));
                    }


                }


            }

但总是有些元素没有被删除,例如 children 的计数是 21,但循环只循环了 10 次。 我怎么解决这个问题?

尝试向后循环,这样您就不会在循环过程中弄乱 collection。

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));
        }
    }
}