【问题标题】:Comparing Datagrid cell original value with edited value in CellEditEnding event比较 Datagrid 单元格原始值与 CellEditEnding 事件中的编辑值
【发布时间】:2015-09-10 13:13:26
【问题描述】:

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

【问题讨论】:

    标签: c# silverlight datagrid


    【解决方案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
            }
    
        }
    
    }
    

    【讨论】:

    • 能否详细说明?
    【解决方案2】:

    您可以通过访问该行的 DataContext 来获取原始值。

    代码sn-p:

    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;
        }
    

    【讨论】:

    • 如果您使用的是 EntityFramework 和数据绑定。您可以从它的 DataContext 中获取单元格的值,就像这样。 ((TheType)((TextBox)e.EditingElement).DataContext).ThePropertyInTheType 这应该是未编辑的值。
    猜你喜欢
    • 2016-03-19
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多