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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With