在CellEditEnding事件中比较数据网格单元格的原始值和编辑后的值
本文关键字:原始 编辑 单元格 网格 事件 CellEditEnding 比较 数据网 数据 | 更新日期: 2023-09-27 17:59:28
我有一个totals变量,它根据用户在我的Datagrid行中输入的数字进行更新。我想在更改每一行单元格时更新该值。这就是我迄今为止所做的:
private void QuotationDG_CellEditEnding(object sender,
DataGridCellEditEndingEventArgs e)
{
int ColumnIndex = e.Column.DisplayIndex;
Double amount= Double.Parse(((TextBox)e.EditingElement).Text);
Cat1SubTotal += amount;
GrandTotal += amount;
}
此代码将用户每次输入新值时的金额相加。但是,如果用户编辑了现有值,那么这将在不删除旧值的情况下添加新值,从而显示不正确的总计。
我需要做这样的事情:
Cat1SubTotal += (NewValue-OriginalValue)
当用户开始编辑时,处理BeginningEdit事件并将值存储在专用变量中。然后将其与CellEditEnding事件中处理的新值进行比较。
public partial class MainWindow : Window
{
private ViewModel VM { get; set; }
private DataGridCellInfo activeCellAtEdit { get; set; }
public MainWindow()
{
InitializeComponent();
this.VM = new ViewModel();
this.DataContext = this.VM;
}
private void MyDataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
this.activeCellAtEdit = MyDataGrid.CurrentCell;
}
private void MyDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
//assumes columns are all TextBoxes
TextBox t = e.EditingElement as TextBox;
string editedCellValue = t.Text.ToString();
//assumes item property bound to datagrid is of type string
string originalValue = activeCellAtEdit.Item.SomeStringProperty;
//compare strings
if(editedCellValue != originalValue)
{
//do something
}
}
}
您可以通过访问行的DataContext来获得原始值。
代码片段:
private void datagrid1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
int ColumnIndex = e.Column.DisplayIndex;
Double amount = Double.Parse(((TextBox)e.EditingElement).Text);
string col = ((System.Windows.Controls.DataGridBoundColumn)(e.Column)).Binding.Path.Path;
double val = Double.Parse(e.Row.DataContext.GetType().GetProperty(col).GetValue(e.Row.DataContext, null).ToString());
Cat1SubTotal += (amount - val);
GrandTotal += amount;
}