2011-02-02 492 views
11

我已經從Codeplex實現了WPF DataGrid Single-Click Editing。 在該解決方案中,單擊的單元格將被聚焦,並選中該行以實現 單擊編輯DataGrid。它效果很好。WPF DataGrid - 如何自動退出編輯模式?

下面的代碼:

private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
    { 
     DataGridCell cell = sender as DataGridCell; 
     if (cell != null && !cell.IsEditing && !cell.IsReadOnly) 
     { 
      if (!cell.IsFocused) 
      { 
       cell.Focus(); 
      } 
      DataGrid dataGrid = FindVisualParent<DataGrid>(cell); 
      if (dataGrid != null) 
      { 
       if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow) 
       { 
        if (!cell.IsSelected) 
         cell.IsSelected = true; 
       } 
       else 
       { 
        DataGridRow row = FindVisualParent<DataGridRow>(cell); 
        if (row != null && !row.IsSelected) 
        { 
         row.IsSelected = true; 
        } 
       } 
      } 
     } 
    }  

但我也希望當單元格值改變我的DataGrid會自動退出編輯模式(不用敲回車鍵) 。例如,我在編輯模式下在單元格中有一個組合框。當用戶在組合框中選擇一個值時,它會自動綁定選定的值。但是用戶仍然需要點擊Enter退出編輯模式。我如何自動退出編輯模式?

我試着偵聽屬性更改並調用DataGrid的CommitEdit函數以自動退出編輯模式。很好用,代碼如下:

void _gameCompareViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) 
    { 
     if (e.PropertyName == "End Edit") 
     { 
      AlignGrid.CommitEdit(); 
     } 

    } 

但是現在單擊編輯功能對當前單元格不起作用。 我必須先點擊不同的行才能使其工作。 我想我想要的是當CommmitEdit被調用時,它會自動選擇一個不同的行 。 (就像當你按Enter鍵時,它會進入下一行) 任何建議傢伙?請告訴我如何做到這一點的代碼。我在這裏爲我的項目耗盡時間。

感謝您的幫助。

+0

什麼的`cell`在`PreviewMouseLeftButtonDown`方法的價值後,你叫編程commitEdit的()?爲什麼該方法無法達到`cell.IsSelect = true`? – Pakman 2011-04-26 03:35:50

回答

7

從單元格編輯模板翻轉回電池模板:

dataGrid.CancelEdit();