如何从动态生成的按钮c#处理事件

时间:2017-06-30 10:29:23

标签: c# xamarin

首先,我是IT开发的新手,我刚刚学习...... 我有一个RunTime按钮,我想处理每个按钮的事件,我该怎么办? 这是我的代码;

  public partial class Dashboard : ContentPage
{

    private IList<Condominium> output;


    public Dashboard(IList<Condominium> output)
    {

        var Buttonadd = new Style(typeof(Button))
        {
            Setters = {
                        new Setter {Property = Button.TextColorProperty, Value = Constants.MainTextColor},
                        new Setter {Property = Button.BackgroundColorProperty, Value = Constants.BackgroundColor},
                        new Setter {Property = Button.HorizontalOptionsProperty, Value = LayoutOptions.FillAndExpand},
                        new Setter {Property = Button.VerticalOptionsProperty, Value = LayoutOptions.FillAndExpand},
                        new Setter {Property = Button.TextProperty, Value = TextAlignment.End},
                        new Setter {Property = Button.WidthRequestProperty, Value = 200},
                        new Setter {Property = Button.HeightRequestProperty, Value = 200},
                       }
        };



        StackLayout parent = new StackLayout();

        foreach (var cond in output)
        {
            Button add = new Button
            {
                Style = Buttonadd,
                Text = cond.Name,
                Margin = new Thickness(0, -10, 0, -10),

            };



            parent.Children.Add(add);


        }


        Content = new ScrollView
        {
            Margin = new Thickness(0, 10, 0, 10),
            BackgroundColor = Color.White,
            Content = parent,
        };


        this.output = output;


        InitializeComponent();
    }



}
}

1 个答案:

答案 0 :(得分:1)

您必须订阅click事件。

您可以阅读按钮事件here

另请参阅EventHandler Delegate以更好地了解Clicked事件处理程序的工作原理。

Button btnToAdd = new Button
{
    Style = Buttonadd,
    Text = cond.Name,
    Margin = new Thickness(0, -10, 0, -10),

};

btnToAdd.Clicked += OnButtonClicked;

parent.Children.Add(add);

然后添加您的事件处理程序:

void OnButtonClicked(object sender, EventArgs e)
{
    //add your code here
}