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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With