在stacklayout中动态添加按钮 [英] Adding buttons dynamically in stacklayout
问题描述
当我单击添加"按钮时,我想在StackLayout
中动态添加按钮.我写了stacklayoutname.children.add(button)
,它没有给我我想要的东西.
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.
在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);
}
它仅提供新按钮,而添加按钮消失,但是我希望每当我们单击添加按钮时,其新按钮数应等于添加按钮的点击数.
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.
推荐答案
由于您已经拥有一个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类和数据绑定基础.
For more information about Binding, check out BindableObject Class and Data Binding Basics.
这篇关于在stacklayout中动态添加按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!