【问题标题】:Xamarin command binding to 2 argument methodsXamarin 命令绑定到 2 个参数方法
【发布时间】:2020-11-14 09:08:13
【问题描述】:

我是新手,对委托和 lambda 语句还不够熟悉。所以它可能太简单了,但这是我的问题:

我正在尝试通过在 Xamarin 中使用命令绑定来实现具有 2 个参数的异步订阅方法。当我编写如下所示的初始化命令时,代码编辑器说

动作不接受两个参数

那么我应该怎么做才能使用两个参数异步方法进行命令绑定?

//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)
{...}

【问题讨论】:

    标签: c# xamarin delegates commandbinding


    【解决方案1】:

    您可以将模型对象作为参数传递,它可以包含多个参数。

    例如:

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

    【讨论】:

      【解决方案2】:

      检查Command 定义here

      Command(Action) 初始化 Command 类的新实例。

      Actiondoes not take any input arguments

      public delegate void Action();
      

      所以你只能用不带参数也不返回任何东西的方法来实例化它

      【讨论】:

      • 同意。但是我需要两个参数来传递给方法。应该有办法的。
      【解决方案3】:

      我找到了一种方法来完成它,传递一个包含所有必要参数的对象。实际上,@Junior Jiang 是这么建议的。但我也希望用单行 lambda 表示法对其进行编码。

      这是我的解决方案。

              public SubscriptionViewModel()
              {
              subscriptionInfo = new SubscriptionInfo("s01", "payload");
      
              Subscribe = new Command<SubscriptionInfo>(async (s) => await GetSubscritionsOptsAsync(this.subscriptionInfo));
          ...
          }
      

      【讨论】:

      • 太棒了!记得尽可能标记答案。如果使用对象作为参数,您可以自定义一个类来处理输入参数。然后外部可以使用一行来初始化对象并使用传递。
      猜你喜欢
      • 2021-02-11
      • 2021-02-02
      • 1970-01-01
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      • 2016-03-05
      • 2016-12-28
      相关资源
      最近更新 更多