Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove children from Panel only if are of type T

Tags:

c#

.net

wpf

panel

I have a WPF Panel (like Canvas for example) and I want to remove its Children only if these children are of type T, for example all of type Button.

How can I do this? Can I use LINQ?

like image 327
Nick Avatar asked Jun 22 '12 17:06

Nick


2 Answers

You can use LINQ, this is one way of doing.

canvas1.Children.OfType<Button>().ToList().ForEach(b => canvas1.Children.Remove(b));

OR you can loop though all the Child elements and if it is button add them to a list and finally remove them. don't remove buttons inside foreach loop.

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 way is more readable and simple and less coding.

like image 123
Damith Avatar answered Oct 19 '22 06:10

Damith


Just do a type comparison. The tricky part is modifying a collection while you're looping through it; I did this by using two for loops:

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

Edit

This way is cleaner, looping from the end of the collection, so as to remove items from inside the loop.

Type t = typeof(Button);
for (int i=MyPanel.Children.Count-1 ; i>=0 ; i--)
{
     if (MyPanel.Children[i].GetType()) == t)
         MyPanel.Children.RemoveAt(i);
}
like image 41
McGarnagle Avatar answered Oct 19 '22 08:10

McGarnagle