12

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.

2
  • 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? Commented Jul 21, 2017 at 5:56
  • 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. Commented Jul 21, 2017 at 6:37

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks it got worked for me.but i would like add command for that newly added button.Is it possible to bind the commands for those buttons
How to give bindings to these buttons
To add binds (Continuing the AddButton method): newButton.BindingContext = yourViewModel; and newButton.SetBinding(Button.CommandProperty, new Binding("CommandPropertyName"));
@sahithi Yes, it is possible. Please check my updated answer. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.