简体   繁体   English

Datagrid列排序生成错误

[英]Datagrid column Sorting generating error

I have a datagrid column whose column values are databound.我有一个数据网格列,其列值是数据绑定的。 I have used DataGridTemplateColumn and i need to use sorting in this column.我使用了 DataGridTemplateColumn 并且我需要在此列中使用排序。

my:DataGridTemplateColumn SortMemberPath="FileName" Header="Name" IsReadOnly="True" MinWidth="150"

It works and sorts the data but when I edit the data after sorting, I need to re-generate the data in the column.它可以工作并对数据进行排序,但是当我在排序后编辑数据时,我需要重新生成列中的数据。

FileListingGrid.ItemsSource = listFiles1;

But this generates "'Sorting' is not allowed during an AddNew or EditItem transaction. "但这会生成“在 AddNew 或 EditItem 事务期间不允许‘排序’。”

It works fine when column data is not sorted but whenever i sort the data and have to re-generate the column data, it throws the following error.当列数据未排序时它工作正常,但每当我对数据进行排序并必须重新生成列数据时,它都会引发以下错误。

There are two ways to resolve this issue有两种方法可以解决这个问题

1) CommitNew() and CommitEdit() before custom sort 1) 自定义排序前的 CommitNew() 和 CommitEdit()

private void DataGrid_ParametersList_Sorting(object sender, DataGridSortingEventArgs e)
{
DataGridColumn column = e.Column;

//prevent the built-in sort from sorting
e.Handled = true;

ListSortDirection direction = (column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;

//set the sort order on the column
column.SortDirection = direction;

//use a ListCollectionView to do the sort.
ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(DataGrid_ParametersList.ItemsSource);

ParametersListComparer customComparer = new ParametersListComparer();
customComparer.SortDirection = direction;
customComparer.SortMemeberPath = column.SortMemberPath;

if (lcv.IsAddingNew) 
lcv.CommitNew();
if (lcv.IsEditingItem)
lcv.CommitEdit();

//apply the sort
lcv.CustomSort = customComparer;
}

2) Another way is Make a Data grid read only. 2)另一种方法是使数据网格只读。

<my:DataGrid x:Name="DataGrid"                             
IsReadOnly="True"
Sorting="DataGrid_Sorting">

After ListCollectiontView.AddNewItem( item );ListCollectiontView.AddNewItem( item ); do not forget ListCollectiontView.CommitNew();不要忘记ListCollectiontView.CommitNew(); This method ends the add transaction and saves the pending new item.此方法结束添加事务并保存挂起的新项目。 Same for CommitEdit()CommitEdit()相同

您可以使用 CollectionViewSource 并指定您的 SortMemberPath(在您的情况下为“文件名”)作为 SortDescription 吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM