TextCell绑定到ViewModel命令中的TapGestureRecognizer

时间:2018-07-30 05:52:37

标签: xamarin xamarin.forms

我有一个用于表节的以下代码段:

  <TableRoot>
    <TableSection Title="First Section">
        <TextCell Text="TextCell 1">
            <TapGestureRecognizer Command="{Binding Source={x:Reference this}, Path=MyCommand}"
              CommandParameter="{value1}"/>
        </TextCell>
        <TextCell Text="TextCell .... n">
            <TapGestureRecognizer Command="{Binding Source={x:Reference this}, Path=MyCommand}"
              CommandParameter="{value..n}"/>
        </TextCell>            
    </TableSection>
  </TableRoot>    

在我的视图模型中,我具有以下绑定:

    public Command MyCommand
    {
        get
        {
            return new Command(p => {
                // option 1
                var name = p.ToString();
                Debug.WriteLine("Here we are ... " + name);
            });
        }
    }

编译时,我不断出现以下错误...

Cannot set the content of the TextCell as it doesn't have a ContentPropertyAttribute

基本上,当我单击TableCell时,在函数MyCommand中,我想从CommandParameter发送值。

您能提供的任何帮助,我将不胜感激。谢谢

2 个答案:

答案 0 :(得分:0)

尝试此代码。可能会有帮助:

     <TableRoot>
    <TableSection Title="First Section">
        <TextCell Text="TextCell 1">
           <TextCell.GestureRecognizers>
               <TapGestureRecognizer Command="{Binding Source={x:Reference this}, Path=MyCommand}"
              CommandParameter="{value1}"/>
           </TextCell.GestureRecognizers>
        </TextCell>
        <TextCell Text="TextCell .... n">
            <TextCell.GestureRecognizers>
                 <TapGestureRecognizer Command="{Binding Source={x:Reference this}, Path=MyCommand}"
              CommandParameter="{value..n}"/>
            </TextCell.GestureRecognizers>
        </TextCell>            
    </TableSection>
  </TableRoot> 

答案 1 :(得分:0)

TextCell中的手势识别器是一个XAML可绑定属性,可以将GestureRecognizor作为其参数,因此您需要执行以下操作:

    <TableRoot>
<TableSection Title="First Section">
    <TextCell Text="TextCell 1">
       <TextCell.GestureRecognizers>
           <TapGestureRecognizer Command="{Binding YourCommandBinding1}"
          CommandParameter="your_binding"/>
       </TextCell.GestureRecognizers>
    </TextCell>
    <TextCell Text="TextCell .... n">
        <TextCell.GestureRecognizers>
             <TapGestureRecognizer Command="{Binding YourCommandBinding2}"
          CommandParameter="your_binding"/>
        </TextCell.GestureRecognizers>
    </TextCell>            
</TableSection>

其中“ CommandParameter”是您在命令中收到的参数,而“ YourCommandBinding”是ViewModel中的ICommand属性,如下所示,可以为其分配System.Windows.Input.Command

Public ICommand YourCommandBinding {get; set;}
YourCommandBinding= new System.Windows.Input.Command(your_Function);

Private void your_Function(object obj)
{
  //Where your obj parameter is the command parameter and you can cast it to your type. 
}