Delete DataGrid row (WPF) by clicking Delete key button
I have WPF 4 desktop-based application. In one of the windows of this application, I have DataGrid
with data, bonded with SQL Server database (via ADO.NET Entity Framework). In order to manipulate data, I have a delete button, that dele开发者_如何学Ctes selected row from DataGrid
and call SaveChanges()
method.
Now I want to add support for keyboard manipulations, e.g. I want to let the user remove the row by selecting and clicking on Delete keyboard button.
If I set CanUserDeleteRows="True"
in window 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
a check if (e.Key == Key.Delete)
, so run remove method that removes selected row and call SaveChanges()
method, but it doesn't work.
How can I add keyboard event handler to DataGrid
?
The purpose to be able removing selected row and calling SaveChanges()
method or just running my own method, that deals with row removing from DataGrid
and making commit to DB.
Of course, if you have any other idea, related to my question, feel free to suggest.
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...
//...
}
}
Or you could use the CommandManager, which only deletes the row if the row is selected (if a cell is editing, it backs up).
Put this in your Window where the Datagrid is located.
CommandManager.RegisterClassInputBinding(typeof(DataGrid),
new InputBinding(DataGrid.DeleteCommand, new KeyGesture(Key.Delete)));
Same as Ben's but all one has to do is enable the property CanUserDeleteRows by setting it to true
and the delete button will have delete active.
As shown below in XAML
for the DataGrid
:
CanUserDeleteRows="True"
I see you managed to go ahead, but maybe this will be useful for others seing this post in search results. You need to override the OnCanExecuteDelete method of the DataGrid, like:
public class MyDataGrid : DataGrid
{
protected override void OnCanExecuteDelete(CanExecuteRoutedEventArgs e)
{
foreach(DataRowView _row in this.SelectedItems) //assuming the grid is multiselect
{
//do some actions with the data that will be deleted
}
e.CanExecute = true; //tell the grid data can be deleted
}
}
But this is just for manipulating pure graphics. For saving to database or other actions use the data source of your data grid.
精彩评论