通过点击删除键按钮删除DataGrid行(WPF)

4
我有一个基于WPF 4的桌面应用程序。在此应用程序的一个窗口中,我有一个带有数据的DataGrid,通过ADO.NET实体框架与SQL Server数据库进行绑定。为了操作数据,我有一个删除按钮,它可以从DataGrid中删除选定的行并调用SaveChanges()方法。
现在我想添加对键盘操作的支持,例如,我想让用户通过选择并单击删除键来删除行。
如果我在窗口XAML中设置CanUserDeleteRows="True",它会删除选定的行,但不会提交到数据库,换句话说,它不会调用SaveChanges()方法。
我尝试向DataGrid添加keyDown事件处理程序,并检查if (e.Key == Key.Delete),然后运行删除选定行的方法并调用SaveChanges()方法,但它不起作用。
如何向DataGrid添加键盘事件处理程序?
目的是能够删除选定的行并调用SaveChanges()方法,或者运行自己的方法,处理从DataGrid中删除行并提交到数据库的操作。
当然,如果您有任何与我的问题相关的其他想法,请随时提出建议。
4个回答

9
你尝试使用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

或者您可以使用CommandManager,仅当选择了行时才删除行(如果单元格正在编辑,则备份)。

将此代码放在包含Datagrid的窗口中。

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

这个代码什么也没做。应该把它放在窗口的构造函数里面吗?还是放在Loaded事件处理程序里面? - Soonts
它应该位于Windows构造函数中。 - Ben Petersen

2
与Ben的方法相同,只需启用属性CanUserDeleteRows并将其设置为true,删除按钮就会变为可用状态。
如下所示,在DataGrid的XAML中:
CanUserDeleteRows="True"

0

我看到你已经取得了进展,但对于在搜索结果中看到此帖子的其他人可能会有所帮助。

您需要覆盖 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
    }
}

但这仅适用于操作纯图形。要保存到数据库或执行其他操作,请使用数据网格的数据源。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接