Search code examples
c#wpfxamlstackpanel

How to remove last children from stack panel in WPF?


I am adding children to my stackpanel dynamically. What I need is, I want to remove the last children for certain scenario. Is there any option to get last children?

Here is my code:

var row = new somecontrol();           
stackpanel.Children.Add(row); 

Is there any possible way to remove children.lastOrDefault()?

stackpanel.Children.Last(); 

Any help would be appreciated. Thanks in advance.


Solution

  • How about:

    if(stackpanel.Children.Count != 0)
        stackpanel.Children.RemoveAt(stackpanel.Children.Count - 1);
    

    ...or if you want to use Linq, just use the OfType<> ExtensionMethod. Then you can do whatever with Linq you wish, like LastOrDefault:

    var child = stackpanel.Children.OfType<UIElement>().LastOrDefault();
    if(child != null)
        stackpanel.Children.Remove(child);
    

    But, the first is probably fastest.

    Or you can make your own Extension method, if you want:

    class PanelExtensions
    {
        public static void RemoveLast(this Panel panel)
        {
            if(panel.Children.Count != 0)
                panel.Children.RemoveAt(panel.Children.Count - 1);
        }
    }
    

    Use like this

    stackpanel.Children.RemoveLast();
    

    But Like Xeun mentions an MVVM solution with Bindings would be preferable.