2017-06-30 51 views
2

首先,我是新的IT开发,我只是学习... 我有一个运行时按钮,我想处理每个按钮的事件,我怎么能做它? 这是我有的代码;如何从动态生成的按钮c处理事件#

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



} 
} 
+0

尝试'add.Click + = YourClickHandler;' – Enigmativity

回答

1

您必须订阅点击事件。

您可以在按钮事件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 
}