wpf datagrid在底部添加新项目,手动排序

时间:2013-12-16 12:30:11

标签: wpf datagrid

我在后面的代码中执行以下操作:当用户单击具有特殊模板的最后一个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;

1 个答案:

答案 0 :(得分:0)

好吧,我的代码在其主要结构中没问题。

我使用默认数据网格和行添加/排序行为再次测试。当新行结束编辑时,添加的行似乎会被排序,这是唯一的区别。

我看了一下在新行结束编辑后添加自动排序但没有成功。我很好,新添加的验证线保持在最低位,所以我会满意地回答我自己的问题。