1

I have defined a model as follows:

public class UserDetails
{
    public int Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public List<Transport> TransportModel { get; set; }
}

Based on the above model, I have instantiated a list that contains hard coded values for testing purposes.

Further, I am dynamically populating buttons based on the TransportModel values on a XAML page as follows:

        StackLayout stack = new StackLayout();

        foreach (var t in user.TransportModel)
        {
// Here I am looping to access data in the TransportModel
            Button btn = new Button();
            btn.Text = t.Name;
            btn.SetBinding(Button.CommandProperty, new Binding("ShowCommandParameter"));
            btn.CommandParameter = user.TransportModel; // if this correct ?
            stack.Children.Add(btn);
        }

And I have the following ViewModel:

 public TransportViewModel()
        {
            ShowCommandParameter = new Command<UserDetails>(Show);
        }

        public void Show(UserDetails param)
        {
        // I want to access properties of TransportModel here..
        }

The issue that I am having is that I want to pass two parameters in the CommandParameter. And I want to access these values within the Show method.

Could someone please help me on this ? I'm totally stuck.

3
  • you should only need to pass a UserDetails object as the parameter, it has all of the data you need Commented Jan 18, 2018 at 16:12
  • @Jason : Is this correct : btn.CommandParameter = t; ? Then how do I access it within the method Show ? Commented Jan 18, 2018 at 16:14
  • I spoke too soon, see my answer below. Commented Jan 18, 2018 at 16:27

1 Answer 1

2

since each button only applies to a specific Transport, you want to pass a Transport object as your CommandParameter

foreach (var t in user.TransportModel)
{
  ...
  btn.CommandParameter = t;
  ...
}

then

    public TransportViewModel()
    {
        ShowCommandParameter = new Command<Transport>(Show);
    }

    public void Show(Transport param)
    {
        // param contains the selected Transport
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a tons brother. You are always helpful :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.