2011-12-22 37 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 }); 
     } 
    } 
}