在 stacklayout 中动态添加按钮 [英] Adding buttons dynamically in stacklayout

查看:41
本文介绍了在 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 Class数据绑定基础.

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

这篇关于在 stacklayout 中动态添加按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆