且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 stacklayout 中动态添加按钮

更新时间:2022-12-23 16:57:05

既然你已经有了一个 StackLayout,就没有必要添加一个新的,因为如果你这样做了,它会替换旧的.下面将在每次单击按钮时向 StackLayout 添加一个按钮.

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);
}

有关绑定的更多信息,请查看BindableObject Class数据绑定基础.

For more information about Binding, check out BindableObject Class and Data Binding Basics.