2013-05-10 80 views
1

我在DataGrid中查找剛剛編輯的單元格的行和單元格索引時出現問題。 我使用CellEditEnding事件來了解單元格編輯的時間。如何獲取DataGrid中剛剛編輯的單元格的行和單元格的索引

直到現在我已經設法做這樣的事情。 Col1包含屬性DisplayIndex,這是選定列的索引,但我找不到相同的方式。

private void DataGridData_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) 
    { 
     DataGridColumn col1 = e.Column; 
     DataGridRow row1 = e.Row; 
    } 

回答

3

我現在正在工作。這是它的樣子:

private void DataGridData_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) 
    { 
     DataGridColumn col1 = e.Column; 
     DataGridRow row1 = e.Row; 
     int row_index = ((DataGrid)sender).ItemContainerGenerator.IndexFromContainer(row1); 
     int col_index = col1.DisplayIndex; 
    } 
0

晚的答案,但任何人誰發現這個問題,這個代碼將加入這個事件到您的DataGrid工作:

private void dgMAQ_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) 
    { 
DependencyObject dep = (DependencyObject)e.EditingElement; 
      string newText = string.Empty; 

     //Check if the item being edited is a textbox 
     if (dep is TextBox) 
     { 
      TextBox txt = dep as TextBox; 
      if (txt.Text != "") 
      { 
       newText = txt.Text; 
      } 
      else 
      { 
       newText = string.Empty; 
      } 
     } 
     //New text is the new text that has been entered into the cell 

     //Check that the value is what you want it to be 
     double isDouble = 0; 
     if (double.TryParse(newText, out isDouble) == true) 
     { 

      while ((dep != null) && !(dep is DataGridCell)) 
      { 
       dep = VisualTreeHelper.GetParent(dep); 
      } 

      if (dep == null) 
       return; 


      if (dep is DataGridCell) 
      { 
       DataGridCell cell = dep as DataGridCell; 

       // navigate further up the tree 
       while ((dep != null) && !(dep is DataGridRow)) 
       { 
        dep = VisualTreeHelper.GetParent(dep); 
       } 

       if (dep == null) 
        return; 

       DataGridRow row = dep as DataGridRow; 
       int rowIndex = row.GetIndex(); 

       int columnIndex = cell.Column.DisplayIndex; 

     //Check the column index. Possibly different save options for different columns 
       if (columnIndex == 3) 
       { 

        if (newText != string.Empty) 
        { 
         //Do what you want with newtext 
        } 
       } 
} 
0

要獲得行索引沒有「發件人」的說法,你可以嘗試:

Convert.ToInt32(e.Row.Header) 

與Patryk的回答這個的縮寫形式相結合,爲:

private void DataGridData_CellEditEnding(DataGridCellEditEndingEventArgs e) 
    { 
     int col1 = e.Column.DisplayIndex; 
     int row1 = Convert.ToInt32(e.Row.Header); 
    } 
相關問題