如何:使用 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# 代码被忽略了——没有升序排序,它只创建了那个显示的小箭头,但项目没有排序。我的错误是什么?
编辑我:
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);
}
编辑二:
public string getSortPropertyName(DataGridColumn col)
{
return "Content";
}