How to remove last children from stack panel in WPF?

自作多情 提交于 2019-12-06 11:38:19

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!