How to remove last children from stack panel in WPF?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-13 19:38:28

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/28208686/how-to-remove-last-children-from-stack-panel-in-wpf

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