将Datagrid单元格原始值与CellEditEnding事件中的已编辑值进行比较

时间:2015-06-24 11:00:56

标签: c# silverlight datagrid

我有一个总计变量,它根据用户在我的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)

2 个答案:

答案 0 :(得分:2)

您可以通过访问行的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;
    }

答案 1 :(得分:1)

处理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
        }

    }

}