如何在WPF数据网格中使用TAB键添加新行

3

当我在datagrid的最后一个单元格上按下“TAB”键时,我希望能添加一行新记录。

我正在使用MVVM模式完成此操作。我已经想到了一个解决方案,将Tab键分配给datagrid的输入绑定:

    <DataGrid.InputBindings>
       <KeyBinding Command="{Binding Path=InsertNewLineCommand}" Key="Tab"></KeyBinding>
   </DataGrid.InputBindings>

将以下代码添加到InsertNewLineCommand:

private void ExecuteInsertNewLineCommand()
    {
        //Checked is SelectedCell[0] at last cell of the datagrid
        {
            InsertNewLine();
        }
    }

但问题在于,如果我添加了KEYBINDING='TAB',那么我的表格的常规TAB功能将被禁用(无法移动到下一个单元格等)。

你似乎已经在检查SelectedCell是否为最后一个了,为什么不在那之后加上一个else语句,并通过编程将SelectedCell移动到DataGrid中的下一个单元格呢? - Kyeotic
1个回答

1

只需确定是否处于最后一列,然后执行您的命令。

我正在使用PreviewKeyDown,因此我可以测试逻辑,但是您可以将其放入executeCommand方法中。无论如何,这应该让您开始:

<DataGrid PreviewKeyDown="DataGrid_PreviewKeyDown" SelectionUnit="Cell" ....

private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (!Keyboard.IsKeyDown(Key.Tab)) return;
    var dataGrid = (DataGrid) sender;

    var current = dataGrid.Columns.IndexOf(dataGrid.CurrentColumn);
    var last = dataGrid.Columns.Count - 1;

    if (current == last)
         ExecuteInsertNewLineCommand();

}


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