如何:使用C#/ WPF对DataGrid的项目进行排序
我确实有以下代码段(不重要的代码已被删除):
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>
不幸的是,C#代码被忽略 - 没有提升排序,它只创建显示的小箭头,但项目没有排序。我的错是什么?
编辑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";
}
答案 0 :(得分:0)
嗯,有一种方法可以让它正常工作。在这里。
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;
}
应该这样做。现在您可以排序,列标题将正确显示排序指标