Phu Minh Pham
Phu Minh Pham

Reputation: 1055

Remove elements from stackpanel

I have a button, when pressed it adds a textbox and a listbox to a stackpanel and adds this stackpanel to another stackpanel named "stackPanelAdd". Just like this:

private void buttonAdd_Click(object sender, RoutedEventArgs e)
{
    StackPanel sp = new StackPanel();
    TextBox tb = new TextBox();   
    ListBox lb = new ListBox();

    tb.Margin = new Thickness(5, 5, 5, 0);
    lb.Margin = new Thickness(5, 5, 5, 0);
    lb.Height = 200;

    sp.Children.Add(tb);
    sp.Children.Add(lb);

    stackPanelAdd.Children.Add(sp);
}

How do I remove the last children in the stackpanel "stackPanelAdd"? Should I use something like stackPanelAdd.children.Remove? if so then how do i get the last element in the stackpanel?

Upvotes: 4

Views: 15763

Answers (4)

Sabeen
Sabeen

Reputation: 53

@Milan Halada's answer worked for me with a little change,

while (stackPanelAdd.Children.Count>0)
{
  stackPanelAdd.Children.RemoveAt(stackPanelAdd.Children.Count-1);
}

so, it removes all the children and then i add new children to it dynamically using for loop, with new data.

Upvotes: 1

Maheep
Maheep

Reputation: 5605

You can use

var lastControl = stackPanelAdd.Children.LastOrDefault(); 
//Last is defined in System.Linq.Enumrable
if(lastControl != null)
    stackPanelAdd.Children.Remove(lastControl);

Upvotes: 1

brunnerh
brunnerh

Reputation: 184622

That is not a good idea, if you stick to this method things will probably get very messy sooner or later. When dealing with items that can be added and removed in WPF you will want to use an ItemsControl of some kind on top of panels (you can change the panel using the ItemsPanel property, by default it will be a StackPanel).

The creation of the controls can also be improved by using data templates and data binding which are core mechanisms that you should become familiar with.

An example:

<ItemsControl ItemsSource="{Binding Data}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBox Text="{Binding Name}" Margin="5,5,5,0"/>
                <ListBox ItemsSource="{Binding Items}" Margin="5,5,5,0" Height="200"/>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Here Data is a source collection which should implement INotifyCollectionChanged, then you can just remove an item from that collection and its corresponding StackPanel will be gone. The items in Data should contain the bound properties Name and Items which you then can assign values to or get entered text from (the class should implement INPC, read more about those things in the article on data binding).

Upvotes: 3

Milan Halada
Milan Halada

Reputation: 1934

Try:

if (stackPanelAdd.Children.Count>0)
{
  stackPanelAdd.Children.RemoveAt(stackPanelAdd.Children.Count-1);
}

Upvotes: 11

Related Questions