Reputation: 33
for(int i = 0; i < stackPanel.Children.Count; i++)
{
stackPanel.Children.Remove(stackPanel.Children[i]);
}
int x = stackPanel.Children.Count();
After running the above code. The controls are still on the screen. Then x equals 33. So how do I really remove the children?
Upvotes: 2
Views: 2369
Reputation: 169420
Could you also explain why they cannot be removed one by one?
Because you are modifying the same collection that you iterate over. So when you remove the element at index 0 and then increment the loop variable to 1, there is new item at index 0 that will never be removed.
You could solve this by iterating backwards. This works:
for (int i = stackPanel.Children.Count - 1; i >= 0; i--)
{
stackPanel.Children.Remove(stackPanel.Children[i]);
}
int x = stackPanel.Children.Count;
Or you could just call the stackPanel.Clear()
method as suggested by @StanleyS.
Upvotes: 1
Reputation: 70701
Without a good Minimal, Complete, and Verifiable code example, it's impossible to know exactly what your code is doing, never mind explain its behavior with certainty.
However, here are some observations:
i
is 0, you remove the first child. But doing so causes the second child to now be the first child. Then you increment i
. So the next time through the loop, you don't remove what was originally the second child, you remove what was originally the third child. And so on.0
, until the collection is empty. Either way, you can also improve efficiency by using the RemoveAt()
method, which removes an element at a specific index, rather than forcing the collection to search until finding the element.Clear()
method. So if you want to remove all of the elements at once, you can use that instead of writing the loop yourself.UIElementCollection
yourself in the first place. If you have dynamic elements like this, you should instead create a view model class to represent each element in the StackPanel
, create instances of that class and add them to e.g. an ObservableCollection<T>
, and then bind that collection to the ItemsSource
of an ItemsControl
that uses a StackPanel
as the ItemsPanel
(which ItemsControl
does by default).Upvotes: 1
Reputation: 1052
stackPanel.Children
returns a UIElementCollection so you can just use Clear()
like this :
stackPanel.Children.Clear()
Upvotes: 1