DataGrid排序升序>降序> null(没有排序)

时间:2013-04-30 11:32:51

标签: wpf sorting datagrid

我试图找到一种方法来配置wpf DataGrid以循环排序:  重复点击时,{升序,降序,无排序}。

我写了这个(但不喜欢它,因此这个q):

<DataGrid AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding DayOfWeek}" >
            <DataGridTextColumn.Header>
                <DataGridColumnHeader PreviewMouseLeftButtonDown="DataGridColumnHeaderClick">Day</DataGridColumnHeader>
            </DataGridTextColumn.Header>
        </DataGridTextColumn>
    </DataGrid.Columns>
    <sys:DateTime>1/2/3</sys:DateTime>
    <sys:DateTime>1/2/4</sys:DateTime>
    <sys:DateTime>1/2/5</sys:DateTime>
</DataGrid>
private void DataGridColumnHeaderClick(object sender, RoutedEventArgs e)
{
    var header = (DataGridColumnHeader) sender;
    if (header.SortDirection == ListSortDirection.Descending)
    {
        header.Column.SortDirection = null;
        e.Handled = true;
    }
}

有没有办法配置DataGrid来执行此操作而不会破坏事件处理程序?

1 个答案:

答案 0 :(得分:4)

尝试使用here建议的解决方案:

<DataGrid AutoGenerateColumns="False" Sorting="DataGridSorting">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Day" Binding="{Binding DayOfWeek}" />
        <DataGridTextColumn Header="Date" Binding="{Binding Date}" />
    </DataGrid.Columns>
    <sys:DateTime>1/1/1</sys:DateTime>
    <sys:DateTime>1/2/1</sys:DateTime>
    <sys:DateTime>1/3/1</sys:DateTime>
</DataGrid>
private void DataGridSorting(object sender, DataGridSortingEventArgs e)
{
    DataGrid dataGrid =(DataGrid) sender;
    string sortPropertyName = e.Column.SortMemberPath;
    if (!string.IsNullOrEmpty(sortPropertyName))
    {
        // sorting is cleared when the previous state is Descending
        if (e.Column.SortDirection.HasValue && e.Column.SortDirection.Value == ListSortDirection.Descending)
        {
            e.Column.SortDirection = null;
            if ((Keyboard.Modifiers & ModifierKeys.Shift) != ModifierKeys.Shift)
            {
                foreach (var sd in dataGrid.Items.SortDescriptions
                    .Where(sd => sd.PropertyName == sortPropertyName).ToList())
                {
                    dataGrid.Items.SortDescriptions.Remove(sd);
                }
            }
            else
            {
                dataGrid.Items.SortDescriptions.Clear();
            }
            dataGrid.Items.Refresh();
            e.Handled = true;
        }
    }
}