WPF Datagrid: Clear column sorting

允我心安 提交于 2019-12-08 15:13:50

问题


I am using a WPF Datagrid in my application where columns can be sorted by clicking on the header.

I was wondering if there was any way to clear a column's sorting programatically ?

I tried sorting a column and then clearing MyDataGrid.Items.SortDescriptions, but that collection was empty (even though one column was sorted).

I also tried :

MyDataGridColumn.SortDirection = null;

The problem is that the column indication is gone, but the sorting still occurs when editing a cell and switching rows.

Is there no way to clear a column's sort ?

Edit (for clarity): The problem is that I'd like to allow sorting again if the user re-clicks on the same column header, so setting CanUserSort to false would be problematic, even if it were done in the XAML. In short, what I'm attempting to do, is prevent rows from being ordered once a sorted column has a cell that was modified. I want to force the user to re-click on the header.


回答1:


Here is what you need:

using System.Windows.Data;
using System.ComponentModel;

ICollectionView view = CollectionViewSource.GetDefaultView(grid.ItemsSource);
if (view != null)
{
    view.SortDescriptions.Clear();
    foreach (DataGridColumn column in grid.Columns)
    {
        column.SortDirection = null;
    }
}

Original source: https://stackoverflow.com/a/9533076/964053

What I want to know is what was M$ thinking for not putting a ClearSort() method...




回答2:


Set CanUserSort to false for all columns -

foreach (var a in MyDataGrid.Columns)
{
    a.CanUserSort = false;
}



回答3:


as an extension...

    public static  void ClearSort(this DataGrid grid)
    {
        var view = CollectionViewSource.GetDefaultView(grid.ItemsSource);
        view?.SortDescriptions.Clear();

        foreach (var column in grid.Columns)
        {
            column.SortDirection = null;
        }
    }



回答4:


In XAML you can turn it off using this code.

<DataGridTextColumn Header="Header Name" CanUserSort="False"/>



回答5:


This is what I use in my program (I have a RESET button and use this to clear the sorting on a datagrid).

System.Windows.Data.CollectionViewSource.GetDefaultView(MY_DATA_GRID.ItemsSource).SortDescriptions.Clear();

Works like a charm.

Cheers, Iato




回答6:


In the XAML code of DataGrid you can add CanUserSortColumns="False". Then noboady would be able to sort any column at rumtime.




回答7:


This is a small code snippet to disable the sorting of DataGridView.

for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
    dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
}


来源:https://stackoverflow.com/questions/13401869/wpf-datagrid-clear-column-sorting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!