2011-12-22 75 views
2

我一直试图谷歌这一点,但一直无法找到适合我的解决方案。在DataGrid中编辑行时检测

我有一个DataGrid显示客户端不知道的SQL表中的一些信息。 客户端只是向服务器发送一个请求,并获取一个列表<SomeClass>作为响应,然后显示在DataGrid中。

我需要检测用户何时对行进行更改,并且需要用户输入的新值。 目前我正在使用RowEditEnding事件。然后,处理此事件的方法可以:

private void editRowEventHandler(object sender, DataGridRowEditEndingEventArgs e) 
{ 
    SomeClass sClass = e.Row.DataContext as SomeClass; 
    // Send sClass to the server to be saved in the database... 
} 

这给了我正在编辑的行。但是它在变化之前给了我一行,我无法弄清楚在变化发生后如何获得这一行。

有没有人知道我可以做到这一点,或者可以指向我可以找到的方向?

+0

为什么不只是在SomeClass集合中捕获它呢? – Paparazzi 2011-12-22 17:52:09

回答

1

就你而言,你试图检测对象的变化。它归结为SomeClass的的属性,所以你需要专注于“细胞”,而不是“行”

假设你的DataGrid是resultGrid,我想出了下面的代码:

resultGrid.CellEditEnding += resultGrid_CellEditEnding; 
void resultGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) 
     { 
      var yourClassInstance = e.EditingElement.DataContext; 
      var editingTextBox = e.EditingElement as TextBox; 
      var newValue = editingTextBox.Text; 
     } 

的“e”还包含有关单元格的行和列的信息。因此,您将知道单元格正在使用哪个编辑器。在这种情况下,我假设它是一个文本框。 希望它有帮助。

+0

希望我只用一行就能得到新的值。因为我有一个有20个成员变量的类。所以我想我必须编写一个开关来查看我正在处理的列,并将值赋给正确的成员变量。 它比我想写的代码更多,但它确实解决了问题,谢谢。 :) – Laleila 2011-12-23 12:46:13

3

请参阅讨论here,以避免读出逐个单元格。

private void OnRowEditEnding(object sender, DataGridRowEditEndingEventArgs e) 
{ 
    DataGrid dataGrid = sender as DataGrid; 
    if (e.EditAction == DataGridEditAction.Commit) { 
     ListCollectionView view = CollectionViewSource.GetDefaultView(dataGrid.ItemsSource) as ListCollectionView; 
     if (view.IsAddingNew || view.IsEditingItem) { 
      this.Dispatcher.BeginInvoke(new DispatcherOperationCallback(param => 
      { 
       // This callback will be called after the CollectionView 
       // has pushed the changes back to the DataGrid.ItemSource. 

       // Write code here to save the data to the database. 
       return null; 
      }), DispatcherPriority.Background, new object[] { null }); 
     } 
    } 
}