The essence of the question is the following: a DataGrid was created and when selecting an Item through

<DataGrid.RowDetailsTemplate> <DataTemplate> <Border BorderBrush="#FF27798B" BorderThickness="1" CornerRadius="2"> <Grid> <Button/> </Grid> </Border> </DataTemplate> </DataGrid.RowDetailsTemplate> 

Data is added for example with a button. When I click on the button, I want to delete the current Item, but since the focus disappears when I press the button, I cannot delete it accordingly.

  • And if the deletion is tied to a simple button outside the data grid, then everything works fine. - Max
  • it's not clear what you're asking for - user227049

1 answer 1

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> 

enter image description here

  • Thank you. All problem at me consisted in a binding. By your example, everything works :) In my case, I just performed the bandage to the delegate and that's it. :) Thanks again - Maxim