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
    };
}

Leave a Comment