Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding buttons dynamically in stacklayout

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.

like image 827
sahithi Avatar asked Jul 21 '17 05:07

sahithi


1 Answers

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.

like image 93
Curiousity Avatar answered Nov 06 '22 20:11

Curiousity