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?
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With