我有一个WPF Panel
(例如Canvas
)我想删除Children
只有当这些子类型为T
时,例如全部输入Button
。
我该怎么做?我可以使用LINQ吗?
答案 0 :(得分:12)
你可以使用LINQ,这是一种做法。
canvas1.Children.OfType<Button>().ToList().ForEach(b => canvas1.Children.Remove(b));
或者你可以循环遍历所有的Child元素,如果是按钮,则将它们添加到列表中,最后删除它们。不要删除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方式更易读,更简单,编码更少。
答案 1 :(得分:3)
只需进行类型比较。棘手的部分是修改一个集合,同时你循环它;我通过使用两个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);
}
答案 2 :(得分:0)
一些LINQ:
panel1.Controls.OfType<Button>().ToList().ForEach((b) => b.Parent = null);
对不起所有的错误家伙。进行了更正和测试。
答案 3 :(得分:0)
通过我的手机取消此功能:
foreach(object o in MyPanel.Children)
{
if(o.GetType() == typeof(Button))
{
MyPanel.Children.Remove(o);
}
}