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?
Button btn = (Button)sender;
People.Remove((Person)btn.DataContext);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With