3

我试图找到一种方法来配置 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 来做到这一点?

4

1 回答 1

4

尝试了这里建议的解决方案,如下所示:

<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;
        }
    }
}
于 2013-04-30T12:11:38.093 回答