【问题标题】:Delete DataGrid row (WPF) by clicking Delete key button通过单击删除键按钮删除 DataGrid 行 (WPF)
【发布时间】:2011-04-29 13:36:41
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: c# wpf xaml datagrid keyboard


    【解决方案1】:

    您是否尝试过 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 处理程序中?
      • 应该位于windows构造函数中
      【解决方案3】:

      与 Ben 的相同,但只需将属性 CanUserDeleteRows 设置为 true 即可启用,删除按钮将激活删除。

      如下图XAMLDataGrid

      CanUserDeleteRows="True"
      

      【讨论】:

        【解决方案4】:

        我看到您成功了,但也许这对在搜索结果中看到此帖子的其他人有用。 您需要重写 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
            }
        }
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-15
          • 2012-10-19
          • 1970-01-01
          • 2015-02-03
          • 1970-01-01
          • 2016-09-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多