如何:对数据网格的项进行排序

本文关键字:排序 网格 数据 数据网 如何 | 更新日期: 2023-09-27 18:04:41

如何使用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);
    }

编辑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;
    }

应该可以了。现在可以排序了,列标题将适当地显示排序指示符