Reputation: 3573
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:
ItemVM
gets instantiatedto custom workflow that does not require explicitly edit the Blank Row first:
ItemVM
gets instantiatedit is not important at which point the new ItemVM
is added to bound ItemsSource
.
Upvotes: 1
Views: 103
Reputation: 169200
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.
Upvotes: 1