views:

26

answers:

2

Hi,

I have WPF 4 desktop-based application. In one of the windows of this application I have DataGrid with data, binded with SQL Server database (via ADO.NET Entity Framework). In order to manipulate with data I have delete button, that deletes selected row from DataGrid and call SaveChanges() method.

Now I want to add support for keyboard manipulations, e.g. i want to let user to remove row by selecting and clicking on Delete keyboard button.

If I set CanUserDeleteRows="True" in window's XAML, it removes selected row, but doesn't make commit to database, in other words, it doesn't call SaveChanges() method.

I tried to add keyDown event handler to DataGrid an check if (e.Key == Key.Delete), so run remove method that removes selected row and call SaveChanges() method, but it doesn't work.

My question is how can I add keyboard event handler to DataGrid that will let remove selected row and call SaveChanges() method or just run my own method, that deals with row removing from DataGrid and make commit to DB.

Of course, if you have any other idea, relatred to my question, feel free to suggest.

Thanks.

+1  A: 

Have you tried with the PreviewKeyDown event? Something like this

<DataGrid x:Name="dataGrid" PreviewKeyDown="dataGrid_PreviewKeyDown">

private void dataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Delete)
    {
        var dataGrid = (DataGrid)sender;
        // dataGrid.SelectedItems will be deleted...
        //...
    }
}
Meleak
A: 

you can try routed command.

1- Create a static routed command.

 public static RoutedCommand DeleteCommand = new RoutedCommand(); 

2- in the constructor of your window add below code. this code will add a CommandBinding as well as a KeyBinding to the datagrid's InputBindings collection.

 public MainWindow()
    {

        CommandBinding delCommandBinding =
        new CommandBinding(DeleteCommand, ExecutedDeleteCommand);
        this.CommandBindings.Add(delCommandBinding); 

        InitializeComponent();
        dataGrid1.CanUserDeleteRows = true;


        dataGrid1.InputBindings.Add(new KeyBinding(DeleteCommand, new KeyGestur(Key.Delete)));


    }

3- Define the eventhandler for the routed command as shown beloe

 private void ExecutedDeleteCommand(object sender, ExecutedRoutedEventArgs e)
    {
          // First get the current selected item by using DataGrid.CurrentItem;
          object obj = dataGrid1.CurrentItem;
          // Since we have overridden defaut delete behaviour of grid, we need to call explicitly run Delete command as shown below or alternatively , you can rebind your grid.
          ApplicationCommands.Delete.Execute(null, dataGrid1);
          // Save deleted data to database by calling appropoiate method.
         SaveData();
    }  

now when you press delete button , ExecutedDeleteCommand will be called in which you can handel , actual source update.

saurabh