简体   繁体   中英

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.

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. "

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

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.

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

After ListCollectiontView.AddNewItem( item ); do not forget ListCollectiontView.CommitNew(); This method ends the add transaction and saves the pending new item. Same for CommitEdit()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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