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.
That should do it. Now you can sort and the column headers will show the sort indicator appropriately