SomethingElse
SomethingElse

Reputation: 97

Add click event to dynamic button in xamarin

I want to add buttons from a list, depending of how many items there are in the list. It works perfectly when I do it like this:

enter image description here

The thing is they have no click events, I want each button to have an event that makes the user navigate to the right page depending on which button is clicked.

I'm trying to do it this way but it doesn't work:

enter image description here

Any ideas of the right way to do it if this is totally wrong?

Upvotes: 1

Views: 3924

Answers (2)

Jesus Angulo
Jesus Angulo

Reputation: 2666

You can try with this.

foreach(var item in question.Answers){

    var button = new Button{Text=item.AnswerText};
    button.Clicked += async(s,e)=> await Navigation.PushAsync(item.NextPage);
    stack.Children.Add(button);
}

Upvotes: 1

Milen
Milen

Reputation: 8867

Create the button before adding in to your StackLayout:

foreach(var item in question.Answers)
{
     var button = new Button();
     button.Text = item.AnswerText;
     button.Clicked += async delegate { await Navigation.PushAsync(item.NextPage); };

     stack.Children.Add(button);
}

Upvotes: 3

Related Questions