Let a collection of goods be displayed in my DataGrid:
public ObservableCollection<ProductVm> Products { get; } = new ObservableCollection<ProductVm>() { new ProductVm { Name = "Молоко", Cost = 59.9m }, new ProductVm { Name = "Хлеб", Cost = 25.0m }, new ProductVm { Name = "Огурцы", Cost = 130.0m }, new ProductVm { Name = "Чай", Cost = 85.9m } };
Let's get the command to remove an item from the collection:
public DelegateCommand DeleteCommand { get; }
And create it in the constructor:
DeleteCommand = new DelegateCommand(o => Products.Remove((ProductVm)o));
The command is very simple, it receives the item in the parameter and removes it from the collection. It remains only to transfer this product to the team, it is very simple, because like any ItemsControl, the DataGrid sets its DataContext to its strings and we can get it using a binding (note the setting of the CommandParameter property):
<DataGrid ItemsSource="{Binding Products}"> <DataGrid.RowDetailsTemplate> <DataTemplate> <Button Content="Удалить" HorizontalAlignment="Right" Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}" CommandParameter="{Binding}"/> </DataTemplate> </DataGrid.RowDetailsTemplate> </DataGrid>
