I'm using the WPF DataGrid
(.Net 3.5 SP 1 version from the Toolkit)
What event can I subscribe to, to detect when a new row is added? (e.g. when the user moves the cursor down or presses Enter a new blank row gets added to the grid).
Eventually what I want to do is use that event to calculate some default values and put them in the new row.
The grid is bound to a DataTable
, if that makes any difference.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With