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));
}
}
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
Make your Questions and Answers containers as ObservableCollections. The the U.I. controls will automatically update when an item is added or removed. No need for RaisePropertyChanged() calls in this case.
I would add a property to your item class.
bool PendingDelete {get; set;} = false;
Then use a CollectionViewFilter to filter out all items marked to be deleted. Pressing the delete button would mark the item for deletion as well as refresh the CollectionView.
When the actual commit command takes place query your collection for all items marked for deletion and process them.
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