3
votes

I want to add a new line in my datagrid when I press 'TAB' key on last cell of the datagrid.

I am using MVVM pattern to do this. I have came with a solution, I assinged Tab key to the Input binding of the datagrid:

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

And added following code to InsertNewLineCommand:

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

But the problem is ON ADDING KEYBINDING='TAB' MY NORMAL TAB FEATURE ON THE GRID DISABLES (MOVING TO NEXT CELL AND SO...)

1
You appear to already be checking to see if the SelectedCell is the last one, why not just add an else after that, and move the SelectedCell to the next cell in the DataGrid programatically?Kyeotic

1 Answers

1
votes

Just determine if you are on the last column then execute your command.

I am using PreviewKeyDown, so I could test the logic, but you can put that in your executeCommand method. Anyway, this should get you started:

<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();

}