If you want to use events to calculate a sum, you might want to check the CellEditEnding
event. However, the better way to go for in WPF is data binding, because it gives you better control on when your data should be updated and it provides a better separation of presentation and business code (which is what MVVM is about).
Data binding means that you create an object that contains your data and connect it with your DataGrid
. The grid will display the information of the object and it will update it when the user changes the grid data. It also automatically performs the necessary conversions. When your object implements the INotifyPropertyChanged
event, the DataGrid
will also be updated when your object changes (regardless of who changed it: the user with an edit or the application in program code). In your case you would need something similar to this:
class ExampleObject : INotifyPropertyChanged {
private int m_value1;
private int m_value2;
public int Value1 {
get {
return m_value1;
}
set {
if (value != m_value1) {
m_value1 = value;
OnPropertyChanged(new PropertyChangedEventArgs(nameof(Value1));
OnPropertyChanged(new PropertyChangedEventArgs(nameof(Sum));
}
}
}
public int Value2 {
get {
return m_value2;
}
set {
if (value != m_value2) {
m_value2 = value;
OnPropertyChanged(new PropertyChangedEventArgs(nameof(Value2));
OnPropertyChanged(new PropertyChangedEventArgs(nameof(Sum));
}
}
}
public int Sum {
get {
return m_value1 + m_value2;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
}
When you bind your data object to the grid, it will discover that it implements INotifyPropertyChanged
and automatically update when you edit the values. Check this post on how to bind your object to the DataGrid
.