How to add a new line on TAB key in WPF dataGrid
I want to add a new line in my datagrid when I press 'TAB' key on开发者_Go百科 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...)
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();
}
精彩评论