Search code examples
c#windowswindows-phone-8windows-phone

Remove all items other then the first one from a StackPanel?


Title says it all - how do remove all of the items, other then the first one, from a stackpanel? Clear() just remove them all and won't work in this case. RemoveAt() doesn't really help. There is no set amount of items that will be in the stackpanel at any given time.


Solution

  • panel.Children.RemoveRange(1, panel.Children.Count - 1);
    

    See the RemoveRange function (MSDN).

    The above code removes all children from the second item to the count - 1 (since you wanted to keep the first element).

    For Windows Phone 8, you don't get that function, so you'll need to do something like this:

    //Reversed to avoid the collection mutation exception
    foreach (UIElement item in panel.Children.Skip(1).Reverse())
        panel.Remove(item);
    

    Not as "clever" but its short, and obvious what you are doing!