0
votes

I have a MainView that contains a DataGrid that displays a collection of ViewModels. I used this http://www.thesilvermethod.com/default.aspx?Id=VMCollectionWrapperSynchronizeaModelcollectionwithaViewModelcollection example to implement the ViewModel Collection.

Within the DataGrid's rows is a button to delete each row. The problem is that when clicked it accesses the delete command from the ViewModel that is within the ViewModel collection. How do I then get this ViewModel to delete itself from within itself?

Options that I have considered but have been unsussesfull include;

  1. Reference the VMcollection in each of the ViewModels that it contains
  2. Reference the model collection in the viewModel that the VMcollection is wrapping
  3. Refference the parent ViewModel in each ViewModel of the VMcollection

I am completely at a lost on what to do and no reseach has shown an answer. Is it possible to redirect the datacontext of each delete button to the parent ViewModel and delete the child ViewModels from there? if so how would I do this and pass in which child ViewModel (grid line) I need to delete?

1

1 Answers

2
votes

In WPF, you can use the relative source to get to the DataContext at the DataGrid level from within the column:

e.g.

<Button Command="{Binding DataContext.DeleteCommand,
                   RelativeSource={RelativeSource AncestorType=DataGrid}}"/>

This will access the delete command from the parent ViewModel

So if you have a delete button in a column in your grid, it will look like this to access the command at the parent view model.

<DataGrid x:Name="DG" ItemsSource="{Binding}" AutoGenerateColumns="False">
 <DataGrid.Columns>
      <DataGridTemplateColumn CellStyle="{StaticResource ResourceKey=Button}">
              <DataGridTemplateColumn.CellTemplate>
                 <DataTemplate>
                      <Button Content="Delete" Command="{Binding DataContext.DeleteCommand,
                          RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
                 </DataTemplate>
             </DataGridTemplateColumn.CellTemplate>
       </DataGridTemplateColumn>
 </DataGrid.Columns>
 </DataGrid>