1
votes

I have a pretty basic Datagrid XAML bound to a CollectionViewSource.

<DataGrid ItemsSource="{Binding Source={StaticResource EditingItemsCollectionViewSource}}"/>

And the Collection View Source is bound to an observable collection of very basic items with 3 numerical values. C# obviously.

I want to be able to add a new row (add a new item) at the bottom of this datagrid by pressing Tab on the keyboard when I am in the last cell of the last row.

Is this possible?

1

1 Answers

0
votes

One possible solution is to programmatically set the property:

dataGrid.AllowUserToAddRows = true;

in order to implement "Add Row" functionality (provided that it was originally set to false, thus the new row was invisible). As per your task definition, it could be triggered by Tab key press (with any additional condition you may add):

private void dataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    try
    {
        if (e.Key == Key.Tab)
        {
            e.Handled = true;
            // your code    
        }
    }
    catch{}
}

You may also want to set some default values for newly created row item by adding event handling procedure:

dataGrid.InitializingNewItem += new InitializingNewItemEventHandler(dataGrid_InitNewItem);
private void dataGrid_InitNewItem(object sender, InitializingNewItemEventArgs e)
{
        // your code
}

Other sample implementations of adding row to WPF DataGrid could be found here: Wpf DataGrid Add new row

Also, pertinent to your description, you can add the item to the underlying ObservableCollection, so it will automatically appear in the DataGrid.

Hope this will help. Best regards,