代码之家  ›  专栏  ›  技术社区  ›  Mike Omeiri Kouider

通过单击Delete key按钮删除DataGrid行(WPF)

  •  4
  • Mike Omeiri Kouider  · 技术社区  · 14 年前

    我有WPF4桌面应用程序。在这个应用程序的一个窗口中,我有 DataGrid 数据网格 SaveChanges() 方法。

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

    CanUserDeleteRows="True" 在窗口XAML中,它删除选定的行,但不向数据库提交,换句话说,它不调用 保存更改() 方法。

    keyDown 事件处理程序 数据网格 支票 if (e.Key == Key.Delete) ,因此运行删除所选行的remove方法并调用 方法,但它不起作用。

    数据网格 保存更改() 方法或只运行我自己的方法,该方法处理从 数据网格

    当然,如果你对我的问题有任何其他想法,请随时提出。

    4 回复  |  直到 6 年前
        1
  •  9
  •   Fredrik Hedblad    14 年前

    你试过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
  •  2
  •   Ben Petersen    13 年前

    或者可以使用CommandManager,它只在选定行时删除该行(如果单元格正在编辑,则会备份)。

    把这个放在Datagrid所在的窗口中。

    CommandManager.RegisterClassInputBinding(typeof(DataGrid),
                    new InputBinding(DataGrid.DeleteCommand, new KeyGesture(Key.Delete)));
    
        3
  •  2
  •   ΩmegaMan    7 年前

    CanUserDeleteRows 设置为 true

    如下所示 XAML 对于 DataGrid

    CanUserDeleteRows="True"
    
        4
  •  0
  •   user3346850    11 年前

    我看到你成功地做到了,但也许这对其他在搜索结果中发表这篇文章的人是有用的。

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

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