I am trying to create a sales app using Xamarin forms but am stuck on adding products to cart. I am using BindableLayout ItemsSource to populate my list horizontally:
<StackLayout BindableLayout.ItemsSource="{Binding NafakaList}" Orientation="Horizontal" Spacing="20"
VerticalOptions="Start">
<BindableLayout.ItemTemplate>
<DataTemplate x:Name="nafakaStackLayout">
<StackLayout VerticalOptions="Start">
<Frame Padding="0" HasShadow="False" HorizontalOptions="Start" VerticalOptions="Start"
CornerRadius="10" HeightRequest="150" WidthRequest="150">
<Image Source="{Binding Image}" Aspect="Fill" HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand" />
</Frame>
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
<StackLayout>
<Label Text="{Binding Name}" TextColor="Black" FontSize="15" x:Name="nameView" />
<Label Text="{Binding Price}" x:Name="Price" Margin="0,-7,0,0" TextColor="#62153B"
FontSize="12" FontFamily="{StaticResource BoldFont}" />
</StackLayout>
<StackLayout Orientation="Horizontal" Margin="0" VerticalOptions="EndAndExpand">
<!--this is the button that I am using to pass data through-->
<Button Command="{Binding .}" BackgroundColor="White" CommandParameter="{Binding Product}"
HeightRequest="35" FontSize="Small" Text="Add to Cart" x:Name="cartAdd"
Clicked="cartAdd_Clicked" />
</StackLayout>
</StackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
This is my list and button click event:
public void cartAdd_Clicked(object sender, EventArgs e)
{
Object commandParameter = ((Button) sender).CommandParameter;
pr = (Product) NafakaList.GetItem(1);
DisplayAlert(pr.Name, "test", "Ok");
}
List:
public List<Product> NafakaList { get => GetProduct(); }
private List<Product> GetProduct(string name)
{
var products = new List<Product>();
products.Add(new Product {ID= 1, Image = "https://images.unsplash.com/photo-1568347355280-d33fdf77d42a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=752&q=80", Name = "Mchele", Price = "2500 tsh" });
products.Add(new Product { ID = 2, Image = "https://images.unsplash.com/photo-1574323347407-f5e1ad6d020b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=680&q=80", Name = "Ngano", Price = "1600 tsh" }); ;
products.Add(new Product { ID = 3, Image = "https://images.unsplash.com/photo-1579705745811-a32bef7856a3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80", Name = "Maharage", Price = "1500 tsh" });
products.Add(new Product { ID = 4, Image = "https://images.unsplash.com/photo-1560705185-d0291220a442?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=667&q=80", Name = "Kunde", Price = "1000 tsh" });
return products;
}
Try This Code also
public void cartAdd_Clicked(object sender, EventArgs e)
{
var item = sender as Button;
var data = item.BindingContext as Product;
...
}