2010-10-23 189 views
4

我有WPF 4基于桌面的应用程序。在这个应用程序的其中一个窗口中,我有DataGrid的数据,与SQL Server数据库绑定(通过ADO.NET实体框架)。为了操作数据,我有一个删除按钮,从DataGrid中删除选定的行并调用SaveChanges()方法。通过单击删除键按钮来删除DataGrid行(WPF)

现在我想添加对键盘操作的支持,例如,我想让用户通过选择并单击删除键盘按钮来删除该行。

如果我在窗口的XAML中设置了CanUserDeleteRows="True",它将删除所选行但不提交数据库,换句话说,它不会调用SaveChanges()方法。

我试着将keyDown事件处理程序添加到DataGrid中,检查if (e.Key == Key.Delete),因此运行remove方法删除所选行并调用SaveChanges()方法,但它不起作用。

我的问题是如何将键盘事件处理程序添加到DataGrid,它将让删除选定的行并调用SaveChanges()方法或只是运行我自己的方法,它处理从DataGrid中删除行并提交到数据库。

当然,如果您有任何其他想法,与我的问题有关,请随时提出建议。

谢谢。

回答

8

您是否尝试过使用PreviewKeyDown事件?事情是这样的

<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... 
     //... 
    } 
} 
2

或者你可以使用的命令管理,如果选择行(如果单元格被编辑,它备份)只删除该行。

把它放在Datagrid所在的窗口中。

CommandManager.RegisterClassInputBinding(typeof(DataGrid), 
       new InputBinding(DataGrid.DeleteCommand, new KeyGesture(Key.Delete))); 
+0

那什么都不做。在窗口的构造函数中,应该在哪里?或在加载处理程序? – Soonts 2016-05-10 20:30:27

+0

它应该位于窗口构造函数中 – 2016-05-24 17:25:33

2

同奔的,但所有一个必须做的是将其设置为true和删除按钮将已删除活动使财产CanUserDeleteRows

如下图所示在XAMLDataGrid

CanUserDeleteRows="True" 
0

我看你设法继续前进,但也许这将是为别人seing这篇文章在搜索结果中非常有用。 你需要重写DataGrid的OnCanExecuteDelete方法,如:

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 
    } 
} 

但是,这只是操纵纯图形。为了保存到数据库或其他操作,请使用数据网格的数据源。