【问题标题】:C# Equivalent of Xaml's CommandParameter="{Binding .}"Xaml 的 CommandParameter="{Binding .}" 的 C# 等效项
【发布时间】:2018-11-02 11:50:30
【问题描述】:

我正在用 C# 编写一些用户界面代码。它具有 ListViewItemSourceList<MyClass>。当我单击一个单元格时,我想将MyClass 的整个对象传递给绑定的命令。

当我在 XAML 中开发它时,我遇到了 CommandParameter="{Binding .}"。这样做我可以发送整个对象。

 <Label.GestureRecognizers>
     <TapGestureRecognizer Command="{Binding BindingContext.MyId, Source={x:Reference MyList}}"
    CommandParameter="{Binding .}" />
    </Label.GestureRecognizers>

我想知道 "{Binding .}" 的 c# 等价物。

【问题讨论】:

    标签: c# xaml xamarin mvvm xamarin.forms


    【解决方案1】:

    "{Binding .}" 简单地等于new Binding(".")。但是CommandParameter="{Binding .}" 等于 `tapGestureRecognizer.SetBinding(TapGestureRecognizer.CommandParameterProperty, new Binding("."))。

    【讨论】:

    • 我已经尝试过了,但是在我的命令方法中,我正在使用 path = "." 获取和绑定对象。 .好吧,这是有道理的,但我想获得 MyClass 的整行对象。
    • @PranayDeep 好的,我知道你想要什么。我会更新我的答案。
    【解决方案2】:

    在花费了近几个小时应用各种排列和组合之后,这是对我有用的“技巧”:

    Label lbl = new Label();
    lbl.SetBinding(Label.TextProperty, modelProperty.Name, BindingMode.TwoWay);
    TapGestureRecognizer tgr= new TapGestureRecognizer
    {
      Command = BindingContext.CellClickedCommand,
    };
    tgr.SetBinding(TapGestureRecognizer.CommandParameterProperty, ".");
    lbl.GestureRecognizers.Add(tgr);
    

    我认为微软必须为 Xamarin 表单提供更好的文档,因为并非所有开发人员都一直在使用 XAML。此外,大多数文档都没有使用 MVVM。

    【讨论】:

      【解决方案3】:

      下面是如何使用 C# 将 TapGestureRecognizerCommandParameterProperty 绑定到 Label 的 Text 属性的示例

      public MainPage()
      {
          var labelTappedGestureRecognizer = new TapGestureRecognizer
          {
              Command = new Command<string>(async labelText => await DisplayAlert("Label Tapped", labelText, "OK"))
          };
      
          var myLabel = new Label
          {
              Text = "This is my label",
              HorizontalOptions = LayoutOptions.Center,
              VerticalOptions = LayoutOptions.Center
          };
      
          myLabel.GestureRecognizers.Add(labelTappedGestureRecognizer);
          labelTappedGestureRecognizer.SetBinding(TapGestureRecognizer.CommandParameterProperty, new Binding(nameof(Label.Text), source: myLabel));
      
          Content = myLabel;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-19
        • 2017-12-18
        • 1970-01-01
        • 1970-01-01
        • 2017-05-07
        • 1970-01-01
        相关资源
        最近更新 更多