Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Button for each ListView Row

Tags:

c#

mvvm

wpf

I have a listview bound to an Observable Collection 'People', People contains persons with the property 'Name', which gives me a table of people.

I want to have a delete button for each row of this table, appearing the last column. Below is a working implementation. However the handler and the XAML are very intertwined, which isn't good. How could I pass which member of People I've deleted?

XAML:

 <ListView ItemsSource="{Binding People}" Name="ListViewPeople">
                        <ListView.View>
                            <GridView>
                                <GridViewColumn>
                                    <GridViewColumnHeader>Names</GridViewColumnHeader>
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <TextBox Text="{Binding Names}"></TextBox>
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>
                                <GridViewColumn>
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <Button Content="Delete" Click="Button_Click_Delete"/>
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>
                            </GridView>
                        </ListView.View>
                 </ListView>

I've managed to implement this with this handler, but as you can see it means the backing code has to know in detail about the view. This gets the index of the delete button pressed from the ListView and goes and removes the value from my observable collection.

c# code:

    private void Button_Click_Delete(object sender, RoutedEventArgs e)
    {
        DependencyObject dep = (DependencyObject)e.OriginalSource;

        while ((dep != null) && !(dep is ListViewItem))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }

        if (dep == null)
            return;

        int index = ListViewPeople.ItemContainerGenerator.IndexFromContainer(dep);

        People.RemoveAt(index);
    }

Is there a way to perhaps pass which member of the observable collection I've deleted to my handler, so that the handler doesn't have to know about there being a listview etc?

like image 483
Nathan Cooper Avatar asked Apr 02 '26 06:04

Nathan Cooper


1 Answers

Button btn = (Button)sender;
People.Remove((Person)btn.DataContext);
like image 57
paparazzo Avatar answered Apr 03 '26 19:04

paparazzo