WPF DataGrid - Event for New Rows?

The event you are looking for is DataGrid.AddingNewItem event. This event will allow you to configure the new object as you want it and then apply it to the NewItem property of the AddingNewItemEventArgs.

XAML:

<DataGrid Name="GrdBallPenetrations"
      ItemsSource="{Binding BallPenetrationCollection}" 
      SelectedItem="{Binding CurrentSelectedBallPenetration}"
      AutoGenerateColumns="False" 
      IsReadOnly="False"
      CanUserAddRows="True"
      CanUserDeleteRows="True"
      IsSynchronizedWithCurrentItem="True"
      AddingNewItem="GrdBallPenetrations_AddingNewItem">

Code behind in C#:

private void GrdBallPenetrations_AddingNewItem(object sender,
    AddingNewItemEventArgs e)
{
    e.NewItem = new BallPenetration
    {
        Id              = Guid.NewGuid(),
        CarriageWay     = CariageWayType.Plus,
        LaneNo          = 1,
        Position        = Positions.BetweenWheelTracks
    };
}

Objects are persisted (inserted or updated) when the user leaves a row that he was editing. Moving to another cell in the same row updates the corresponding property through data binding, but doesn't signal the Model (or the Data Access Layer) yet. The only useful event is DataGrid.RowEditEnding. This is fired just before committing the modified row.

XAML

<DataGrid ... 
          RowEditEnding="MyDataGrid_RowEditEnding">
</DataGrid>

Code Behind

private void MyDataGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) 
{    // Only act on Commit
    if (e.EditAction == DataGridEditAction.Commit)
    {
         var newItem = e.Row.DataContext as MyDataboundType;
         if (newItem is NOT in my bound collection) ... handle insertion...
    } 
}

All credits for this solution go to Diederik Krolls (Original Post). My respect.

Tags:

C#

Wpf

Datagrid