Reputation: 419
short structure of my project is (using MVVM Light Toolkit):
View (UserControl) with DataGrid
ViewModel
DataAccess with ValueObjects
DB
I'm using an ObservableCollection for DataBinding to my DataGrid, but I stuck at removing a Row in Datagrid and save it to DataBase.
In older projects I used CommandManager.PreviewExecuted event from System.Windows.Input and there I checked event args for the DataGrid.DeleteCommand. Simply this:
if(e.Command == DataGrid.DeleteCommand)
{
DataAccessContext.Sample.DeleteOnSubmit(data);
DataAccessContext.SubmitChanges();
}
I've googled for a few hours now but don't get the right way. I tried to use PassEventArgsToCommand, but the Event DataGrid.DeleteCommand or CommandManager.PreviewExecuted is not firing, SelectionChangedCommand works well, but I don't know how to check it for the important DataGrid.DeleteCommand.
Here's my xaml:
<DataGrid x:Name="dataGrid1" ItemsSource="{Binding Items}" CanUserAddRows="True" CanUserDeleteRows="True" AutoGenerateColumns="False" Height="391" HorizontalAlignment="Left" VerticalAlignment="Top" Width="auto" Margin="2,0,0,0" RowEditEnding="dataGrid1_RowEditEnding" CellEditEnding="dataGrid1_CellEditEnding">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<cmd:EventToCommand
Command="{Binding SelectionChangedCommand,Mode=OneWay}"
CommandParameter="{Binding SelectedItems,ElementName=dataGrid1}">
</cmd:EventToCommand>
</i:EventTrigger>
<i:EventTrigger EventName="DataGrid.DeleteCommand"> //I've also tried PreviewExecuted and CommandManager.PreviewExecuted as EventName
<cmd:EventToCommand
Command="{Binding SelectedItems,Mode=OneWay}"
CommandParameter="{Binding ExecutedRoutedEventArgs, ElementName=dataGrid1}"
PassEventArgsToCommand="True"
></cmd:EventToCommand>
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name, UpdateSourceTrigger=PropertyChanged}" Width="auto"></DataGridTextColumn>
<DataGridTextColumn Header="Vorname" Binding="{Binding Surname, UpdateSourceTrigger=PropertyChanged}" Width="auto"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
Thanks for your answers and best regards
Upvotes: 0
Views: 1108
Reputation: 2957
Try disabling the delete on the DataGrid and instead hook up the Delete key to a command (via KeyBinding) which will do your saving and remove the row from the source collection.
Take a look at this question.
Upvotes: 0