2017-09-15 65 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