Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf DataGrid - Sort on Command only

Tags:

c#

wpfdatagrid

I have my own DataGrid component (inherited from DataGrid). I want this component to act like a MS Access grid. What I need is to sort the data once, when I invoke the method MySort() (MyDataGrid.MySort)

The MySort method uses DataGrid items collection, so I add SortDescription to Items and the View Sorts. The problem is that I don't want to re-sort this grid when an item is added or edited. Sorting might be invoked only by the MySort method.

How to prevent DataGrid from sorting when Items.SortDescription has some values? I need some property like do_not_resort.

like image 407
tomatino Avatar asked Jun 23 '26 07:06

tomatino


1 Answers

If you are using .Net framework 4 or above you can use the "CanUserSortColumns" property of the grid control to prevent automatic sorting.

And the MySort method of your custom grid can roughly look something like this.

public void MySort(DataGridSortingEventArgs args)
    {
        //create a collection view for the datasource binded with grid
        ICollectionView dataView = CollectionViewSource.GetDefaultView(this.ItemsSource);
        //clear the existing sort order
        dataView.SortDescriptions.Clear();

        ListSortDirection sortDirection = args.Column.SortDirection ?? ListSortDirection.Ascending;
        //create a new sort order for the sorting that is done lastly
        dataView.SortDescriptions.Add(new SortDescription(args.Column.SortMemberPath, sortDirection));

        //refresh the view which in turn refresh the grid
        dataView.Refresh();
    }
like image 140
Suresh Kumar Veluswamy Avatar answered Jun 25 '26 21:06

Suresh Kumar Veluswamy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!