2017-09-15 22 views
0

我想创建一个列表视图,用户可以选择列表项来查看商店,也可以点击图像将它们带到产品详细信息中。 如何在ViewCell中添加命令?如何使用MVVM在xamarin listview中添加多个命令按钮?

<ListView ItemsSource="{Binding myData}" x:Name="myListView" SelectedItem="{Binding SelectedStore}" > 
<ListView.ItemTemplate> 
    <DataTemplate> 
     <ViewCell> 
     <Grid>  
       <Label Text="{Binding Title}" /> 
       <Image Source="product.png" > 
        <Image.GestureRecognizers> 
         <TapGestureRecognizer Command="{Binding ItemTapCommand}" CommandParameter="Id" /> 
        </Image.GestureRecognizers> 
       </Image> 
      </Grid> 
     </ViewCell> 
    </DataTemplate> 
</ListView.ItemTemplate> 


    public ICommand ItemTapCommand => new Command(ShowSelectedProductAsync()); 

    private async Task ShowSelectedProductAsync() 
    { 
     //take them to view the item detail 
    } 

回答

1

的问题是,你试图绑定到不位于ListView控件中的各个项目的命令; Image上的BindingContext是myData集合中的单个项目。

对于其他框架,例如Wpf,您只需使用绑定的RelativeSource部分来告诉控件在另一个控件的BindingContext上查找您的命令,但这在Xamarin Forms中是不可能的(RelativeSource is不支持)。

你可以做的是下面的,但它需要你的用户控件有一个x:Name

<TapGestureRecognizer Command="{Bindind Path=BindingContext.ItemTapCommand, 
             Source={x:Reference MyUserControl}}" 
         CommandParameter="{Binding Id}" /> 

它说的是使用用户控件作为源的结合,并且属性是嵌套该UserControl由BindingContext.ItemTapCommand组成的属性。

作为奖励,我更新了代码,因为我觉得您可能意味着将每条记录的Id属性的值绑定为命令参数,而不仅仅是发送字符串“Id”作为命令参数。

+0

我不清楚UserControl上。此代码位于xaml页面中,我没有将其用作嵌入xaml页面的usercontrol。你是这个意思吗?如果不是什么将MyUserControl? – wil

+0

@wil:在具有正确的'BindingContext'的xaml图形中的更高位置。我假定它是一个'UserControl',但它可以很容易地成为一个'Page'或其他更高级别的东西。哎呀,你甚至可以使用ListView,因为它已经有一个名字(myListView)。 –

+0

这就是我的想法。非常感谢。今晚我会试试这个。 – wil