Практическое руководство. Сортировка элементов DataGrid с использованием С#/WPF
У меня есть следующие фрагменты кода (неважный код был удален):
С#:
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>
К сожалению, код С# игнорируется - сортировка по возрастанию отсутствует, она создает только ту маленькую стрелку, которая отображается, но элементы не сортируются. Какая у меня ошибка?
Изменить 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);
}
Редактировать II:
public string getSortPropertyName(DataGridColumn col)
{
return "Content";
}
Ну, есть способ заставить его работать нормально. Вот.
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;
}
Это должно сделать это. Теперь вы можете сортировать, и заголовки столбцов будут правильно отображать индикатор сортировки