Xamarin command binding to 2 argument methods

223 Views Asked by At

I am newbie and I am not familiar enough with delegates and lambda statements. So it might too simple but here is my issue:

I am trying to implement async subscription method with 2 argument by using command binding in Xamarin. When I wrote the command initializing shown below, code editor says

Action does not take two arguments

So what should I do to utilize two argument async methods for command binding?

//Command initializing line cause an error which says " Action<object> does not take two arguments. 
Subscribe = new Command(async (productId,payload) => await SubscribeAsync(productId,payload));
....
public async Task<bool> SubscribeAsync(string productId, string payload)
{...}
3

There are 3 best solutions below

1
TiTus On BEST ANSWER

I found a way to accomplish it, passing an object which contain all necessary parameters. Actually, @Junior Jiang suggested that. But I was also looking to code it in one-line lambda notation.

Here is my solution.

        public SubscriptionViewModel()
        {
        subscriptionInfo = new SubscriptionInfo("s01", "payload");

        Subscribe = new Command<SubscriptionInfo>(async (s) => await GetSubscritionsOptsAsync(this.subscriptionInfo));
    ...
    }
1
Athanasios Kataras On

Check the Command definition here

Command(Action) Initializes a new instance of the Command class.

The Action class does not take any input arguments:

public delegate void Action();

So you can only instantiate it with a method that takes no parameters and returns nothing

0
Junior Jiang On

You could pass a model object as paramater, and it could contain more than one argument.

For example:

ICommand SubscribeCommand = new Command((parmaters) => {
    var item = (parmaters as CheckItem);
    var one = item.productId;
    var two = item.payload;
});

CheckItem.cs:

public class CheckItem 
{

    public string productId { set; get; }

    public string payload { set; get; }

}