我有一个WPF Panel
(比如Canvas
),我想只删除它的Children
,如果这些子元素是类型T
,例如所有类型为Button
的元素。
我该怎么做?我可以使用LINQ吗?
你可以使用LINQ,这是一种方法。
canvas1.Children.OfType<Button>().ToList().ForEach(b => canvas1.Children.Remove(b));
或者您可以循环遍历所有子元素,如果它是按钮,则将它们添加到列表中,最后将它们删除。不要在foreach循环内部删除按钮。
List<Button> toRemove = new List<Button>();
foreach (var o in canvas1.Children)
{
if (o is Button)
toRemove.Add((Button)o);
}
for (int i = 0; i < toRemove.Count; i++)
{
canvas1.Children.Remove(toRemove[i]);
}
LINQ的方式更易读、简单,而且编码量更少。
只需要进行类型比较。棘手的部分是在循环遍历集合时对其进行修改;我通过使用两个for循环来解决了这个问题:
var ToRemove = new List<UIElement>();
Type t = typeof(Button);
for (int i=0 ; i<MyPanel.Children.Count ; i++)
{
if (MyPanel.Children[i].GetType()) == t)
ToRemove.Add(MyPanel.Children[i]);
}
for (int i=0 ; i<ToRemove.Length ; i++) MyPanel.Children.Remove(ToRemove[i]);
编辑
这种方法更加清晰,从集合的末尾循环,以便在循环内删除项目。
Type t = typeof(Button);
for (int i=MyPanel.Children.Count-1 ; i>=0 ; i--)
{
if (MyPanel.Children[i].GetType()) == t)
MyPanel.Children.RemoveAt(i);
}
MyPanel.Children.Count - 1
开始,否则会抛出 IndexOutOfRangeException
。 - Nikola Anusev一些LINQ:
panel1.Controls.OfType<Button>().ToList().ForEach((b) => b.Parent = null);
对于所有的错误,我很抱歉。已经进行了更正并测试通过。
panel1.Control
b) 惰性求值(Select
不会立即执行空赋值)。 - L.B这是我在手机上随手写的:
foreach(object o in MyPanel.Children)
{
if(o.GetType() == typeof(Button))
{
MyPanel.Children.Remove(o);
}
}