如果点击“添加”按钮,我想在StackLayout
中动态添加按钮。我写了stacklayoutname.children.add(button)
,它没有给我我想要的东西。
在xaml:
<StackLayout x:Name="layout">
<Button Text="add" Clicked="Addbutton"/>
</StackLayout>
在代码中:
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);
}
它只给出了新的按钮,添加按钮正在消失,但是我想每当我们点击添加按钮时,它应该给新按钮的数量等于添加按钮的点击次数。
答案 0 :(得分:3)
由于您已经有了StackLayout,因此无需添加新的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);
}