I have in my WPF form a DataGrid that is showing items from a DataContext via Binding. I have added a column with delete buttons that are bound to a command in the ViewModel that is supposed to remove the item from the context, and update the DataGrid accordingly.
XAML
<DataGrid ItemsSource ="{Binding Quiz.Questionnaire}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Vraag" Binding="{Binding Content, Mode=TwoWay}"></DataGridTextColumn>
<DataGridTextColumn Header="Aantal antwoorden" Binding="{Binding AnswerCount, Mode=OneWay}" IsReadOnly="True"></DataGridTextColumn>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Delete" Command="{Binding Path=DataContext.DeleteRow, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"
CommandParameter="{Binding Path=SelectedItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
ViewModel
public void DeleteRowCommand(object row)
{
if(row is QuestionVM question)
{
_Context.Questions.Remove(question.ToModel);
RaisePropertyChanged(nameof(Quiz.Questionnaire));
}
else if(row is AnswerVM answer)
{
_Context.Answers.Remove(answer.ToModel);
RaisePropertyChanged(nameof(Answers));
}
}
- I've confirmed that the code properly calls the method, so it's not a problem with the Binding.
- I've confirmed that the database does get properly updated with I click my button that contains the
DataContext.SaveChanges().
What I want, however, is that the DataGrid removes the item from the list before I save the changes. So that I can still discard the changes if I want to.
Update
Basically I'm trying to create an Edit window in which I can edit an item however I want, and then either confirm my changes or change my mind and go back to the previous view and discard all the changes I've made.
To that end, I have my Edit window's ViewModel create its own instance of the DataContext. If I click the Save Changes button, that context is sent back to the previous window and the database is updated accordingly, but if I press Discard Changes, I simply close the window and continue with the old, unedited context.
To be clear, right now I just want the Delete button mentioned in the OP to immediately remove (visually) its row from the DataGrid list