2013-12-16 55 views
0

我在後面的代碼中執行以下操作:當用戶點擊到具有特殊模板的最後一個datagrid項目時,我向收集視圖添加一個新項目,然後按降序排序新添加的空白行位於底部。然後我以編程方式將這個新項目切換到編輯模式。wpf datagrid在手動排序的底部添加新項目

但是,在這一點上,項目沒有得到直觀的排序,當我完成新行版本後,第一次點擊標題時,似乎。標題圖標雖然變化。新行顯示在正確的地方供版本使用。

謝謝你指導我。

  DataGridRow row = sender_ as DataGridRow; 

      if (row.Item != CollectionView.NewItemPlaceholder || row.Template != _adressesDataGridNewRowControlTemplate) return; 

      // In case we click on dedicated bottom line with special template 
      // (it's tuned new item placeholder, we've setup datagrid with CanUserAddRows   
      // to false 

      // 1. Globally commit datagrid (there are validations errors but we're willing to keep them) 
      AddressGrid.CommitEdit(); 
      AddressGrid.UpdateLayout(); 

      // 2. Add a new item to collection view 
      ListCollectionView view = (ListCollectionView)CollectionViewSource.GetDefaultView(AddressGrid.ItemsSource); 
      view.AddNewItem(new Adresse()); 
      view.CommitNew(); 
      view.Refresh(); 

      // 3. Programmatically descending sorting... new item will be at bottom 
      // right below new item placeholder 

      foreach (DataGridColumn dataColumn in AddressGrid.Columns) 
       dataColumn.SortDirection = null; 

      DataGridColumn selectedDataColumn = AddressGrid.Columns[1]; 
      selectedDataColumn.SortDirection = ListSortDirection.Descending; 
      view.SortDescriptions.Clear(); 
      view.SortDescriptions.Add(new SortDescription(selectedDataColumn.Header as string, ListSortDirection.Descending)); 
      view.Refresh(); 

      // 4. Get this added line reference 
      int iAddedLineIndex = AddressGrid.Items.Count - 2; 
      row = ObjectTreeHelper.GetRow(AddressGrid, iAddedLineIndex); 
      // apply edit template 
      row.Template = _adressesDataGridDefaultRowControlTemplate; 
      AddressGrid.UpdateLayout(); 

      // 5. Go to edition mode 
      AddressGrid.CurrentItem = row.Item; 

      // Set focus to desired cell (2nd here) 
      DataGridCell cell = ObjectTreeHelper.GetCell(AddressGrid, iAddedLineIndex, 1); 
      cell.Focus(); 
      AddressGrid.BeginEdit(); 

      // 6. Consider left mouse click event as handled 
      e_.Handled = true; 

回答

0

那麼,我的代碼在其主要結構中是OK的。

我再次使用默認數據網格和行添加/排序行爲進行測試。當新行結束編輯時,似乎添加的行會進行排序,這是唯一的區別。

我看了一下關於在新行結束編輯後添加自動排序,但沒有成功。我很滿意新增的驗證線路保持在最低限度,所以我會滿意的回答自己的問題。