遍历WPF中的控件,最简单的方法时foreach,如Grid中有2个Ellipse和若干个Line,我想找到这两个Ellipse,直接使用foreach就可以了
foreach(var v in Grid1.Children)
{
if(v is Ellipse)
.......
}
但如果是找到这些控件并将其删除,就不能用foreach语句了
foreach(var v in Grid1.Children)
{
if(v is Ellipse)
{
Grid1.Children.Remove(v);
}
}
如果使用上述方法,会出现”因为集合已更改,枚举器无效。”的错误
此时可以使用VisualTreeHelper 类中提供的方法
VisualTreeHelper.GetChildrenCount 方法:返回指定可视对象包含的子级个数
VisualTreeHelper.GetChild 方法:返回指定父可视对象中位于指定集合索引位置的子可视对象
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(Grid1); i++)
{
var child = VisualTreeHelper.GetChild(Grid1, i);
if (child is Ellipse)
Grid1.Children.Remove((Ellipse) child);
}