How to: Sort items of a DataGrid using C# / WPF
I do have the following code snippets (unimportant code has been removed):
C#:
lastName.SortDirection = ListSortDirection.Ascending;
XAML:
<DataGrid AutoGenerateColumns="False" Name="dataGrid_Content">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding lastName}" Header="Nachname" x:Name="lastName" />
</DataGrid.Columns>
</DataGrid>
Unfortunately, the C# code is ignored - there is no ascending sorting, it only creates that little arrow which shows up, but the items are not sorted. What is my mistake?
Edit I:
public void SetItemsToDataContext()
{
dataGrid_Content.Items.Clear();
foreach (string s in Directory.GetFiles(@"C:\Users\...", "*.txt"))
{
StreamReader streamReader = new StreamReader(s);
int i = 1;
string line = streamReader.ReadToEnd().Replace("\n", "");
string[] t = line.Split('\r');
BusinessContact businessContact = new BusinessContact();
businessContact.firstName = t[i + 2];
businessContact.lastName = t[i + 3];
dataGrid_Content.Items.Add(businessContact);
streamReader.Close();
}
applySortDescriptions(lastName, ListSortDirection.Ascending);
}
Edit II:
public string getSortPropertyName(DataGridColumn col)
{
return "Content";
}
Well, there is a way to get it working properly. Here it is.
private void applySortDescriptions(DataGridColumn col, ListSortDirection listSortDirection)
{
//Clear current sort descriptions
MyDataGrid.Items.SortDescriptions.Clear();
//Get property name to apply sort based on desired column
string propertyName = getSortPropertyName(col);
//Add the new sort description
MyDataGrid.Items.SortDescriptions.Add(new SortDescription(propertyName, listSortDirection));
//apply sort
applySortDirection(col, listSortDirection);
//refresh items to display sort
MyDataGrid.Items.Refresh();
}
private string getSortPropertyName(DataGridColumn col)
{
//place logic in here that will return the name of the property to sort by (ex: return “name”; if you are sorting by the name property)
return string.Empty;
}
private void applySortDirection(DataGridColumn col, ListSortDirection listSortDirection)
{
foreach (DataGridColumn c in PatientsViewDatGrid.Columns)
{
c.SortDirection = null;
}
col.SortDirection = listSortDirection;
}
That should do it. Now you can sort and the column headers will show the sort indicator appropriately