1
votes

I would like my <DataGrid/> with CanUserAddItems="true" to instatiate the new ItemVM when the Blank Row gains focus intead of the default behaviour, to create new ItemVM when the blank row is first edited. Or in other words, I would like to change the default DataGrid's workflow from:

  1. User enters Blank Row
  2. User presses F2
  3. New ItemVM gets instantiated

to custom workflow that does not require explicitly edit the Blank Row first:

  1. User enters Blank Row
  2. New ItemVM gets instantiated

it is not important at which point the new ItemVM is added to bound ItemsSource.

1

1 Answers

1
votes

The DataGrid class uses a private AddNewItem method to instantiate the underlying data object.

If you get a reference to the row container for the placeholder, you could handle its GotFocus event and call the AddNewItem() method using reflection:

private void DataGrid_Loaded(object sender, RoutedEventArgs e)
{
    DataGridRow newItemPlaceholderRow = (DataGridRow)dg.ItemContainerGenerator.ContainerFromItem(CollectionView.NewItemPlaceholder);
    if (newItemPlaceholderRow != null)
        newItemPlaceholderRow.GotFocus += (ss, ee) =>
        {
            typeof(DataGrid).GetMethod("AddNewItem",
                System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
                .Invoke(dg, null);
        };
}

Note that AddNewItem() is undocumented and may be modified or removed in future versions, but if you really want to modify the behvaiour of the built-in the control, the other option would probably be to create your custom own one.