Xamarin表单 - 如何在单击"删除"按钮时从列表视图获取产品



列表视图中的每个项目都会添加一个"删除"按钮,当用户单击删除按钮时,它将调用RemoveItemFromShoppingList((并从购物车列表中删除产品。

我已经测试过调用RemoveItemFromShoppingList((并从购物列表中删除第一个项目。这一切都很好,是新的购物车列表更新。

但是,我想删除用户点击的产品,而不是删除第一个项目。我已经尝试捕获ProductId,但无法获得…请通知

<ContentPage.Content>
<StackLayout>
<ListView ItemsSource="{Binding ShoppingListItemSource}" HasUnevenRows="True" SeparatorVisibility="None">
<ListView.Footer>
<Label x:Name="Total" HorizontalTextAlignment="End" VerticalTextAlignment="Start" Margin="20,20" FontAttributes="Bold"/>
</ListView.Footer>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="10" RowSpacing="10" ColumnSpacing="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Text="{Binding ProductId}" VerticalOptions="End" IsVisible="False"/>
<controls:CircleImage  Grid.Column="1"  Grid.Row="1" HeightRequest="60" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" Aspect="AspectFill" WidthRequest="66" Grid.RowSpan="2" Source="{Binding Img}"/>
<Label Grid.Column="2" Grid.Row="1" Text="{Binding Name}" VerticalOptions="End"/>
<Label Grid.Column="2" Grid.Row="2" VerticalOptions="Start" Text="{Binding Detail}"/>
<Label Grid.Column="3" Grid.Row="2" VerticalOptions="Start" Text="{Binding TotalPrice, StringFormat='£{0:0.00}'}"/>

<Label Grid.Column="4" Grid.Row="2" VerticalOptions="Start" Text="{Binding QuantityOfProduct}"/>
<Label Grid.Column="5" Grid.Row="2" VerticalOptions="Start" Text="{Binding SubTotal, StringFormat='£{0:0.00}'}"/>
<Button Grid.Column="6" Grid.Row="2" VerticalOptions="Start" Text="Delete" Clicked="RemoveItemFromShoppingList" Grid.RowSpan="2" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>

这些都不起作用。有人能告诉我如何在点击删除时获得产品id吗?感谢

void RemoveItemFromShoppingList(object sender, EventArgs e)
{
//How can I get Id of product the user wishes to delete
//have tried many things...


//  var productToRemove = (Button)sender;
// Product product = new Product();
//var p_Id = int.Parse(productToRemove.ProductId.ToString());
//product.ProductId = productId;

//var product = ((Button)sender).BindingContext;
//  var productId = product.id;    

//Button button = (Button)sender;
//var imt = (Grid)button.Parent;
//var c = (Label)imt.Children[0];
}

使用BindingContext-这假设您的ItemsSourceProduct类型的集合

void RemoveItemFromShoppingList(object sender, EventArgs e)
{
var button = (Button)sender;
var item = (Product)button.BindingContext;
...
}

最新更新