Adding buttons dynamically in stacklayout
10,301
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.
Related videos on Youtube
Author by
sahithi
Updated on September 14, 2022Comments
-
sahithi over 1 year
I would like to add a button dynamically in
StackLayout
when "add" button is clicked. I wrotestacklayoutname.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.
-
Curiousity almost 7 yearsIt 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 onButton
'sText
?
-