11
votes

I would like to add a button dynamically in StackLayout when "add" button is clicked. I wrote stacklayoutname.children.add(button), it does not giving me the thing i am looking for.

In xaml:

<StackLayout x:Name="layout">
    <Button Text="add" Clicked="Addbutton"/>
</StackLayout>

In code:

private void Addbutton(object sender, EventArgs e)
{           
     var layout = new StackLayout();
     var btn = new Button { Text = "New button", FontSize = 30, TranslationY = 30 };
     this.Content = layout;
     layout.Children.Add(btn);
}

It is giving only new button and add button is disappearing, but I want whenever we click on add button it should give number of new button equal to the number of clicks on add button.

1
It disappears because it's being replaced by the new StackLayout. And when you say should give number of new button equal to the number of clicks on add button, do you mean you want to add buttons as per each click or just display number of clicks on Button's Text?Curiousity
thanks for response,yeah i wanted to add those many buttons as number of clicks but not just display number of clicks on Button's Text.sahithi

1 Answers

8
votes

Since you already have a StackLayout, there's no need to add a new one, because it replaces the old one if you do. The following will add a button to the StackLayout on every button click.

// Define a field for StackLayout
StackLayout parent;

public void Addbutton(object sender, EventArgs e)
{
    // Define a new button
    Button newButton = new Button { Text = "New Button" };

    // Creating a binding
    newButton.SetBinding(Button.CommandProperty, new Binding ("ViewModelProperty"));

    // Set the binding context after SetBinding method calls for performance reasons
    newButton.BindingContext = viewModel;

    // Set StackLayout in XAML to the class field
    parent = layout;

    // Add the new button to the StackLayout
    parent.Children.Add(newButton);
}

For more information about Binding, check out BindableObject Class and Data Binding Basics.