Reputation: 2113
The order of rows in my DataGrid does not change as it should when I click on a column header. I've implemented a custom sorter and this is the prototype of my Compare-Function, which is successfully being called:
public int Compare(object x, object y)
{
var rowView1 = x as DataRowView;
var rowView2 = y as DataRowView;
var row1 = rowView1.Row;
var row2 = rowView2.Row;
var row1Id = Convert.ToInt32(row1[0]);
var row2Id = Convert.ToInt32(row2[0]);
if (SortDirection == ListSortDirection.Ascending)
{
return row1Id.CompareTo(row2Id);
}
else
{
return row2Id.CompareTo(row1Id);
}
}
The compare function above seems to work as suggested, it simply compares Ids and in debug mode, I see that the comparisons lead to valid returns ( +1 or -1). Hower, the order of elements in the datagrid does not change. What am I missing out here? I've googled for so long that I'm close to needing glasses.. thanks for any help!
EDIT: the xaml for my grid
<DataGrid result:CustomSortBehaviour.AllowCustomSort="True"
Name="ResultDataGrid"
IsReadOnly="True"
ItemsSource="{Binding ResultDataTable}">
</DataGrid>
Upvotes: 0
Views: 280
Reputation: 1493
The property you actually need to set is CanUserSortColumns
So set that to true and then if that doesn't work do this.
<DataGrid Sorting="OnDataGridSort"
CanUserSortColumns="True"
Name="ResultDataGrid"
IsReadOnly="True"
ItemsSource="{Binding ResultDataTable}">
</DataGrid>
And then all you need to give the ListcollectionView an instance of your comparer.
void OnDataGridSort(object sender, System.Windows.Controls.DataGridSortingEventArgs e)
{
DataGrid dg = sender as DataGrid;
ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(dg.ItemsSource);
lcv.CustomSort = [Your IComparer instance here];
e.Handled;
}
Upvotes: 1
Reputation:
Add this to your code
allowsorting="true"
You can Use This.
<DataGrid allowsorting="true" result:CustomSortBehaviour.AllowCustomSort="True" Name="ResultDataGrid" IsReadOnly="True" ItemsSource="{Binding ResultDataTable}">
</DataGrid>
Upvotes: 0