Delete item from list using data templates delete button?

Mark Connelly 41 Reputation points
2021-06-14T14:52:42.047+00:00

Hey,

I'm currently trying to delete an item from a list using a button on each of the lists items. Inside this list is a datatemplate with a view cell but I'm unsure how to get the items data when the button is tapped.

I'll post my code below.

xaml

 <ListView x:Name="listView" Background="Black"  SeparatorColor="{DynamicResource SeparatorColor}" SeparatorVisibility="Default" Margin="0" ItemsSource="{Binding BasketList}" HasUnevenRows="True" HeightRequest="250">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <StackLayout Margin="0">
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto"></RowDefinition>
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="50"></ColumnDefinition>
                                        <ColumnDefinition Width="Auto"></ColumnDefinition>
                                        <ColumnDefinition Width="50"></ColumnDefinition>
                                    </Grid.ColumnDefinitions>

                                    <ImageButton Source="editicon.png" VerticalOptions="Center" HorizontalOptions="StartAndExpand" Grid.Row="0" Grid.Column="0" Command="{Binding EditCommand}"></ImageButton>

                                    <StackLayout Grid.Column="1" Grid.Row="0" Orientation="Horizontal" Margin="5" HorizontalOptions="Start">
                                        <Label Text="{Binding ItemQuantity}" TextColor="{DynamicResource PrimaryFontColor}" FontSize="26" HorizontalOptions="Start" Padding="5" VerticalOptions="Center"  FontAttributes="Italic" FontFamily="FetteEng"/>
                                        <Label Text="{Binding ItemName}" TextColor="{DynamicResource PrimaryFontColor}" FontSize="28" LineBreakMode="CharacterWrap" HorizontalOptions="Center" Padding="5" VerticalOptions="Center"  FontAttributes="Italic" FontFamily="FetteEng"/>
                                        <Label Text="{Binding ItemPrice}" TextColor="{DynamicResource PrimaryFontColor}" FontSize="24" HorizontalOptions="End" Padding="5" VerticalOptions="Center"  FontAttributes="Italic" FontFamily="FetteEng"/>
                                    </StackLayout>

                                    <ImageButton Clicked="ImageButton_Clicked"  Source="deleteicon.png" VerticalOptions="Center" HorizontalOptions="Start" Grid.Row="0" Grid.Column="2" Padding="10" Command="{Binding DeleteCommand}"></ImageButton>
                                </Grid>
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

code behind:

 void ImageButton_Clicked(System.Object sender, System.EventArgs e)
        {
              var vm = BindingContext as BasketPageViewModel;

               var button = sender as Button;

        }

So in essence, delete an item using the delete button that's present at each of the list items displays.

Thanks!

Developer technologies .NET Xamarin
0 comments No comments
{count} votes

Accepted answer
  1. Kyle Wang 5,531 Reputation points Microsoft External Staff
    2021-06-15T02:04:13.737+00:00

    Hi MarkConnelly-6630,

    Welcome to our Microsoft Q&A platform!

    As alessandrocaliaro said, you can use relative bindings to access the viewmodel(BindingContext) of this Page.

    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
                 xmlns:local="clr-namespace:deleteitem"  
                 x:Class="deleteitem.MainPage"  
                 x:Name="ListviewPage">  
      
        <ContentPage.BindingContext>  
            <local:MainPageViewModel/>  
        </ContentPage.BindingContext>  
          
        <StackLayout>  
            <ListView x:Name="listView"  ...>  
                <ListView.ItemTemplate>  
                    ...  
                    <ImageButton  Source="deleteicon.png" VerticalOptions="Center" HorizontalOptions="Start" Grid.Row="0" Grid.Column="2" Padding="10"   
                                      Command="{Binding Source={RelativeSource AncestorType={x:Type local:MainPageViewModel}}, Path=DeleteCommand}"  
                                      CommandParameter="{Binding .}"></ImageButton>  
                </ListView.ItemTemplate>  
            </ListView>  
        </StackLayout>  
    </ContentPage>  
    

    And then declare the DeleteCommand in the viewmodel.

    class MainPageViewModel  
    {  
        public ObservableCollection<Basket> BasketList { get; set; }  
      
        public ICommand DeleteCommand { get; }  
      
        public MainPageViewModel()  
        {  
            BasketList = new ObservableCollection<Basket>();  
            BasketList.Add(...);  
            DeleteCommand = new Command<Basket>(DeleteItem);  
        }  
      
        public void DeleteItem(Basket basket)  
        {  
            var deletedItem = basket as Basket;  
            if (basket == null)  
                return;  
            BasketList.Remove(basket);  
        }  
    }  
    

    Another way, you can also use x:Reference.

    <ImageButton  Source="deleteicon.png" VerticalOptions="Center" HorizontalOptions="Start" Grid.Row="0" Grid.Column="2" Padding="10"   
                      Command="{Binding Source={x:Reference Name=ListviewPage}, Path=BindingContext.DeleteCommand}"  
                      CommandParameter="{Binding .}"></ImageButton>  
    

    Regards,
    Kyle


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Alessandro Caliaro 4,196 Reputation points
    2021-06-14T16:08:14.447+00:00

    I think you can use relative bindings

    relative-bindings

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.