At the moment I'm having a working DataGrid in my app and a Model class, which holds changes in DataGrid waiting for user to accept them by pressing a certain button.
It would be great if I could get edited Row information as an object array (column values) so that I won't have to edit other logic of my app.
Here is my event handler for RowEditEnding event:
//Handle row change event while editing
public void DataGridRowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
//Adding confirmation button and so on...
//Save row changes to model
//to update on confirm
var change = ((DataRowView)e.Row.DataContext).Row.ItemArray;
model.updateData.Add(change);
}
However, DataContext doesn't change within an event handler and I'm not able to call Refresh() on DataGrid. I've explored DataGridRowEditEndingEventArgs through debugger but still haven't found the desired information 'bout changes in modified row.
Any ideas on how to make it work?
CodePudding user response:
- Try to call
CommitEdit()
on theDataGrid
before accessing the values in your event handler
Or
- Set the
UpdateSourceTrigger
property of the column bindings toPropertyChanged
CodePudding user response:
Well, I finally came up with this:
As I'm using confirmation button to trigger update, I can use this event to get edited rows. Thus, I've created 2 lists in Model:
public List<object[]> updateData = new();
public List<DataGridRow> updateDataRaw = new();
The "raw" list is used to store DataGridRow information on DataGrid RowEditEnding event:
//Handle row change event while editing
public void DataGridRowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
//Adding confirmation button and so on...
//Save row changes to model
//to update on confirm
var change = e.Row;//Store DataGridRow information
model.updateDataRaw.Add(change);
}
Then I added some code to my confirmation button handler:
private async void ConfirmEditChangesAsync(object sender, RoutedEventArgs e)
{
bool tableUpdated;
try
{
//Get actual Row information
model.GetActualUpdateData();
//Update table according to changes
tableUpdated = await model.UpdateTableAsync(/*my params*/);
//...other code for this handler
And then in Model class I can get DataContext from stored DataRowView and get edited row data from there:
public void GetActualUpdateData()
{
updateData.Clear();
foreach (var data in updateDataRaw)
{
var dataRowView = (DataRowView)data.DataContext;
updateData.Add(dataRowView.Row.ItemArray);
}
updateDataRaw.Clear();
}
Finally, I can use actual data for updated rows in my model.UpdateTableAsync() method.
I guess it's not the best way, but it's working.