Search code examples
c#wpf

C# WPF remove everythin from StackPanel except specific item


I have a StackPanel that holds Usercontrols, these UserControls are replaced, animated, etc on user input. At specific times I would like to make sure that only the currently active view is present in the stackpanel. I tried with a function like this

 public void cleanupStackPanel(UserControl ctrl)
        {
            foreach (UserControl item in contentContainer.Children)
            {
                if(item != ctrl)
                {
                    contentContainer.Children.Remove(item);
                }
            }
        }

But upon calling, it says "enumerator is not valid because the collection changed". How could I change this to achieve the result I want?


Solution

  • You cannot remove items inside of an foreach loop. Use a for loop instead, but be careful: when removing items you have to manipulate the index parameter too!

     public void cleanupStackPanel(UserControl ctrl)
     {
         for ( int i = 0; i < contentContainer.Children.Count; i++ )
         {
             var item = (UserControl) contentContainer.Children[i];
             if(item != ctrl)
             {
                 contentContainer.Children.Remove(item);
                 i--;
             }
         }
     }
    

    I could not test this code, because your example is missing of the surrounded class. So I guessed that contentContainer.Children has a Count property ... but instead it could also be Length. But I am sure, you will find the correct way of determining the number of children ;)