在stacklayout中动态添加按钮

sah*_*thi 8 xamarin xamarin.forms

我想在StackLayout点击"添加"按钮时动态添加一个按钮.我写道stacklayoutname.children.add(button),它没有给我我想要的东西.

在xaml中:

<StackLayout x:Name="layout">
    <Button Text="add" Clicked="Addbutton"/>
</StackLayout>
Run Code Online (Sandbox Code Playgroud)

在代码中:

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);
}
Run Code Online (Sandbox Code Playgroud)

它只给出了新的按钮,并且添加按钮正在消失,但是我想每当我们点击添加按钮时它应该给新按钮的数量等于添加按钮的点击次数.

Cur*_*ity 6

由于您已经有了StackLayout,因此无需添加新的布局,因为如果这样做,它将替换旧的布局。以下操作将StackLayout在每次单击按钮时添加一个按钮。

// 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);
}
Run Code Online (Sandbox Code Playgroud)

有关绑定的更多信息,请在此处此处检查