简体   繁体   中英

WPF datagrid fire sorting event in code

I have some code which listens to the "sorting"-event of a datagrid to be able to add a custom sorter...

I add this when the datagrid has loaded.

grid.Sorting += (sender, args) =>
            {
                var column = (DataGridCustomTextColumn) args.Column;



                //i do some custom checking based on column to get the right comparer
                //i have different comparers for different columns. I also handle the sort direction
                //in my comparer

                // prevent the built-in sort from sorting
                args.Handled = true;

                var direction = (column.SortDirection != ListSortDirection.Ascending)
                    ? ListSortDirection.Ascending
                    : ListSortDirection.Descending;

                //set the sort order on the column
                column.SortDirection = direction;

                //use a ListCollectionView to do the sort.
                var lcv = (ListCollectionView) CollectionViewSource.GetDefaultView(grid.ItemsSource);

                //this is my custom sorter it just derives from IComparer and has a few properties
                //you could just apply the comparer but i needed to do a few extra bits and pieces
                var comparer = new DataGridCommonSort(column.RealDataType, column.SortMemberPath, direction);

                //apply the sort
                lcv.CustomSort = comparer;

            };

The problem is that this handler gets only called when I click the columnheader. But I need a way to initialy fire this event that the data gets sorted

Any ideas? I tried something like:

ICollectionView dataView = CollectionViewSource.GetDefaultView(dataGrid.ItemsSource);
            dataView.SortDescriptions.Clear();
            dataView.SortDescriptions.Add(new SortDescription(c.SortMemberPath, ListSortDirection.Descending));
            dataView.Refresh();

but this doesn't work for me.

You could define the event handler as a (nonanonymous) method:

private void grid_Sorting(object sender, DataGridSortingEventArgs args)
{
    //same code as before...
}

...and simply call it after you have set the ItemsSource property:

grid_Sorting(grid, new DataGridSortingEventArgs(grid.Columns[0])); //sort by the first column

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM